/**
 * Elementor frontend handler — Product Notice widget.
 *
 * Drives the optional dismiss button. When "Remember Dismissal" is on, the
 * closed state is stored in localStorage so the notice stays hidden for the
 * visitor on subsequent visits.
 *
 * @package captain-widgets-kit
 * @since   1.4.0
 */
( function ( $, window, document ) {
	'use strict';

	var STORE_PREFIX = 'captwiki_pnotice_';

	/**
	 * Safe localStorage read.
	 *
	 * @param {string} key Storage key.
	 * @return {boolean} Whether the notice was dismissed before.
	 */
	function wasDismissed( key ) {
		try {
			return window.localStorage.getItem( STORE_PREFIX + key ) === '1';
		} catch ( e ) {
			return false;
		}
	}

	/**
	 * Safe localStorage write.
	 *
	 * @param {string} key Storage key.
	 */
	function remember( key ) {
		try {
			window.localStorage.setItem( STORE_PREFIX + key, '1' );
		} catch ( e ) {}
	}

	/**
	 * Per-instance handler.
	 *
	 * @param {HTMLElement} root Widget wrapper (.captwiki-pnotice).
	 */
	function setupInstance( root ) {
		if ( ! root || root.captwikiPnoticeReady ) {
			return;
		}
		root.captwikiPnoticeReady = true;

		if ( root.getAttribute( 'data-dismissible' ) !== '1' ) {
			return;
		}

		var persist = root.getAttribute( 'data-persist' ) === '1';
		var key     = root.getAttribute( 'data-key' ) || '';
		var btn     = root.querySelector( '.captwiki-pnotice__close' );

		// Already dismissed in a previous visit.
		if ( persist && key && wasDismissed( key ) ) {
			root.classList.add( 'is-dismissed' );
			return;
		}

		if ( ! btn ) {
			return;
		}

		btn.addEventListener( 'click', function () {
			root.classList.add( 'is-dismissing' );

			if ( persist && key ) {
				remember( key );
			}

			window.setTimeout( function () {
				root.classList.add( 'is-dismissed' );
			}, 260 );
		} );
	}

	if ( typeof jQuery !== 'undefined' ) {
		$( window ).on( 'elementor/frontend/init', function () {
			if ( window.elementorFrontend && elementorFrontend.hooks ) {
				elementorFrontend.hooks.addAction(
					'frontend/element_ready/captwiki-woo-product-notice.default',
					function ( $scope ) {
						setupInstance( $scope[ 0 ].querySelector( '.captwiki-pnotice' ) || $scope[ 0 ] );
					}
				);
			}
		} );
	}

	document.addEventListener( 'DOMContentLoaded', function () {
		document.querySelectorAll( '.captwiki-pnotice--dismissible' ).forEach( setupInstance );
	} );

} )( window.jQuery, window, document );
