/**
 * Hafenstudios Core - Admin-JS (Vanilla, kein Framework).
 * Persistiert geschlossene Hans-Karten und zeigt Meilenstein-Toasts.
 */
( function () {
	'use strict';

	var cfg = window.hafenstudiosCore || {};

	function apiFetch( path, body ) {
		if ( window.wp && window.wp.apiFetch ) {
			return window.wp.apiFetch( { path: 'hafenstudios/v1' + path, method: 'POST', data: body } );
		}
		return fetch( cfg.restUrl + path, {
			method: 'POST',
			headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': cfg.nonce },
			body: JSON.stringify( body )
		} );
	}

	function onDismiss( event ) {
		var btn = event.target.closest( '[data-hans-dismiss]' );
		if ( ! btn ) {
			return;
		}
		var card = btn.closest( '[data-hans-card]' );
		var id = btn.getAttribute( 'data-hans-dismiss' );
		if ( card ) {
			card.parentNode.removeChild( card );
		}
		apiFetch( '/hans/dismiss', { card_id: id } );
	}

	function init() {
		document.addEventListener( 'click', onDismiss );

		// Meilenstein-Toasts, serverseitig als data-Attribute hinterlegt.
		var toasts = document.querySelectorAll( '[data-hans-toast]' );
		Array.prototype.forEach.call( toasts, function ( el ) {
			setTimeout( function () {
				el.parentNode && el.parentNode.removeChild( el );
			}, 6000 );
		} );
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}
} )();
