/**
 * Speed in China — anonymous-mode admin notice dismiss handler.
 *
 * Listens for clicks on the WP core ".notice-dismiss" button inside our
 * anonymous-mode notice and fires an AJAX request so the per-user "dismissed"
 * flag is persisted in user meta. Stays out of the global namespace.
 *
 * Configuration is injected via wp_localize_script as `speeinchAnonNotice`:
 *   - ajaxurl: admin-ajax.php URL
 *   - action:  AJAX action name
 *
 * The CSRF nonce is read from the notice element's data attribute so we don't
 * leak it via a globally scoped JS object.
 */
( function () {
    'use strict';

    if ( typeof window.speeinchAnonNotice === 'undefined' || ! window.fetch ) {
        return;
    }

    var config = window.speeinchAnonNotice;

    document.addEventListener( 'click', function ( ev ) {
        var target = ev.target;
        if ( ! target || ! target.classList || ! target.classList.contains( 'notice-dismiss' ) ) {
            return;
        }

        var notice = target.closest( '.speeinch-anonymous-notice' );
        if ( ! notice ) {
            return;
        }

        var nonce = notice.getAttribute( 'data-speeinch-dismiss-nonce' );
        if ( ! nonce ) {
            return;
        }

        var data = new FormData();
        data.append( 'action', config.action );
        data.append( '_wpnonce', nonce );

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