/**
 * Wohno settings — live shortcode generator.
 *
 * Reads the controls in [data-wohno-gen-root], builds a `[wohno_listings …]`
 * shortcode (omitting empty/default values) and keeps it in sync. Admin-only,
 * dependency-free.
 */
( function () {
	'use strict';

	var root = document.querySelector( '[data-wohno-gen-root]' );
	if ( ! root ) {
		return;
	}

	var output = root.querySelector( '[data-wohno-gen-output]' );
	var copyBtn = root.querySelector( '[data-wohno-gen-copy]' );
	var columnsField = root.querySelector( '[data-wohno-gen-columns]' );
	var preview = root.querySelector( '[data-wohno-gen-preview]' );
	var controls = root.querySelectorAll( '[data-attr]' );
	var cfg = window.wohnoGen || {};

	// Stable attribute order for a tidy, predictable shortcode.
	var ORDER = [
		'city', 'zip', 'q', 'property_type', 'rooms_min', 'rooms_max',
		'rent_max', 'wbs_only', 'layout', 'columns', 'limit', 'search', 'load_more'
	];

	function collect() {
		var vals = {};
		controls.forEach( function ( inp ) {
			var attr = inp.getAttribute( 'data-attr' );
			if ( 'checkbox' === inp.type ) {
				if ( inp.checked ) {
					vals[ attr ] = inp.hasAttribute( 'data-checked' ) ? inp.getAttribute( 'data-checked' ) : null;
				} else {
					vals[ attr ] = inp.hasAttribute( 'data-unchecked' ) ? inp.getAttribute( 'data-unchecked' ) : null;
				}
			} else {
				var v = ( inp.value || '' ).trim();
				var def = inp.getAttribute( 'data-default' ) || '';
				vals[ attr ] = ( '' === v || v === def ) ? null : v;
			}
		} );

		// `columns` only applies to the grid layout; `grid` is the default → omit.
		if ( 'grid' !== vals.layout && null !== vals.layout ) {
			vals.columns = null;
		}
		if ( 'grid' === vals.layout ) {
			vals.layout = null;
		}
		return vals;
	}

	function build() {
		var vals = collect();

		if ( columnsField ) {
			var layoutSel = root.querySelector( '[data-attr="layout"]' );
			columnsField.style.display = ( layoutSel && 'grid' === layoutSel.value ) ? '' : 'none';
		}

		var parts = ORDER.filter( function ( k ) {
			return null !== vals[ k ] && undefined !== vals[ k ];
		} ).map( function ( k ) {
			return k + '="' + vals[ k ] + '"';
		} );

		output.textContent = '[wohno_listings' + ( parts.length ? ' ' + parts.join( ' ' ) : '' ) + ']';
		schedulePreview();
	}

	// Explicit attribute values for the server-rendered preview (unlike the
	// shortcode string, defaults are sent too so the render is unambiguous).
	function previewAtts() {
		var a = {};
		controls.forEach( function ( inp ) {
			var attr = inp.getAttribute( 'data-attr' );
			if ( 'checkbox' === inp.type ) {
				a[ attr ] = inp.checked
					? ( inp.getAttribute( 'data-checked' ) || '1' )
					: ( inp.getAttribute( 'data-unchecked' ) || '0' );
			} else {
				a[ attr ] = ( inp.value || '' ).trim();
			}
		} );
		return a;
	}

	var previewTimer = null;
	function schedulePreview() {
		if ( ! preview || ! cfg.ajaxUrl ) {
			return;
		}
		clearTimeout( previewTimer );
		previewTimer = setTimeout( runPreview, 450 );
	}

	function runPreview() {
		preview.innerHTML = '<p class="wohno-gen__preview-loading">' + ( cfg.loading || '…' ) + '</p>';

		var body = new URLSearchParams();
		body.set( 'action', cfg.action || 'wohno_preview' );
		body.set( 'nonce', cfg.nonce || '' );
		var atts = previewAtts();
		Object.keys( atts ).forEach( function ( k ) {
			body.set( 'atts[' + k + ']', atts[ k ] );
		} );

		fetch( cfg.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			body: body.toString(),
		} )
			.then( function ( r ) {
				return r.json();
			} )
			.then( function ( res ) {
				if ( res && res.success && res.data && res.data.html ) {
					preview.innerHTML = res.data.html;
					// Wire up gallery + modal on the freshly injected cards.
					document.dispatchEvent( new CustomEvent( 'wohno:listings-appended' ) );
				} else {
					preview.innerHTML = '<p class="wohno-error">' + ( cfg.error || 'Error' ) + '</p>';
				}
			} )
			.catch( function () {
				preview.innerHTML = '<p class="wohno-error">' + ( cfg.error || 'Error' ) + '</p>';
			} );
	}

	controls.forEach( function ( inp ) {
		inp.addEventListener( 'input', build );
		inp.addEventListener( 'change', build );
	} );

	if ( copyBtn ) {
		copyBtn.addEventListener( 'click', function () {
			var text = output.textContent;
			var done = function () {
				var label = copyBtn.textContent;
				copyBtn.textContent = copyBtn.getAttribute( 'data-copied' ) || 'Kopiert ✓';
				setTimeout( function () {
					copyBtn.textContent = label;
				}, 1500 );
			};
			if ( navigator.clipboard && navigator.clipboard.writeText ) {
				navigator.clipboard.writeText( text ).then( done, done );
			} else {
				var sel = document.createRange();
				sel.selectNodeContents( output );
				var s = window.getSelection();
				s.removeAllRanges();
				s.addRange( sel );
				try {
					document.execCommand( 'copy' );
				} catch ( e ) {}
				s.removeAllRanges();
				done();
			}
		} );
	}

	build();

	/* ---- Single-listing picker: select → [wohno_listing id="…"] ---- */
	var pick = document.querySelector( '[data-wohno-single]' );
	var pickOut = document.querySelector( '[data-wohno-single-output]' );
	var pickCopy = document.querySelector( '[data-wohno-single-copy]' );
	if ( pick && pickOut ) {
		var renderSingle = function () {
			var id = pick.value;
			pickOut.textContent = id ? '[wohno_listing id="' + id + '"]' : '[wohno_listing id="…"]';
		};
		pick.addEventListener( 'change', renderSingle );
		renderSingle();
		if ( pickCopy ) {
			pickCopy.addEventListener( 'click', function () {
				var text = pickOut.textContent;
				var done = function () {
					var label = pickCopy.textContent;
					pickCopy.textContent = pickCopy.getAttribute( 'data-copied' ) || 'Kopiert ✓';
					setTimeout( function () {
						pickCopy.textContent = label;
					}, 1500 );
				};
				if ( navigator.clipboard && navigator.clipboard.writeText ) {
					navigator.clipboard.writeText( text ).then( done, done );
				} else {
					done();
				}
			} );
		}
	}
} )();
