/* Wohno "load more" — cursor-based pagination. Vanilla JS, event-delegated. */
( function () {
	'use strict';

	document.addEventListener( 'click', function ( e ) {
		var btn = e.target.closest ? e.target.closest( '.wohno-load-more' ) : null;
		if ( ! btn ) {
			return;
		}
		e.preventDefault();

		var cfg = window.wohnoLoadMore || {};
		if ( ! cfg.ajaxUrl || 'true' === btn.getAttribute( 'aria-busy' ) ) {
			return;
		}

		var wrap = btn.closest( '.wohno-listings-wrap' );
		var grid = wrap ? wrap.querySelector( '[data-wohno-grid]' ) : null;
		if ( ! grid ) {
			return;
		}

		btn.setAttribute( 'aria-busy', 'true' );
		btn.disabled = true;

		var body = new URLSearchParams();
		body.set( 'action', cfg.action || 'wohno_load_more' );
		body.set( 'nonce', cfg.nonce || '' );
		body.set( 'query', btn.getAttribute( 'data-wohno-query' ) || '{}' );
		body.set( 'cursor', btn.getAttribute( 'data-wohno-cursor' ) || '' );

		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 ) {
				btn.removeAttribute( 'aria-busy' );
				btn.disabled = false;

				if ( ! res || ! res.success || ! res.data ) {
					btn.parentNode.removeChild( btn );
					return;
				}
				if ( res.data.html ) {
					grid.insertAdjacentHTML( 'beforeend', res.data.html );
					// Let the gallery/modal script wire up the new cards.
					document.dispatchEvent( new CustomEvent( 'wohno:listings-appended' ) );
				}
				if ( res.data.has_more && res.data.next_cursor ) {
					btn.setAttribute( 'data-wohno-cursor', res.data.next_cursor );
				} else {
					btn.parentNode.removeChild( btn );
				}
			} )
			.catch( function () {
				btn.removeAttribute( 'aria-busy' );
				btn.disabled = false;
			} );
	} );
} )();
