/**
 * Craft Addons - dashboard.
 *
 * Locked (Pro) toggles are clickable: instead of being disabled, a click opens
 * a branded "upgrade" dialog. Closes on the X, the backdrop or Escape.
 */
( function () {
	'use strict';

	var modal = document.getElementById( 'cafw-pro-modal' );
	if ( ! modal ) {
		return;
	}

	var lastFocus = null;

	function open( trigger ) {
		lastFocus = trigger || document.activeElement;
		modal.hidden = false;
		document.body.classList.add( 'cafw-modal-open' );
		var close = modal.querySelector( '.cafw-modal__close' );
		if ( close ) {
			close.focus();
		}
	}

	function close() {
		if ( modal.hidden ) {
			return;
		}
		modal.hidden = true;
		document.body.classList.remove( 'cafw-modal-open' );
		if ( lastFocus && typeof lastFocus.focus === 'function' ) {
			lastFocus.focus();
		}
	}

	document.querySelectorAll( '[data-cafw-pro]' ).forEach( function ( trigger ) {
		trigger.addEventListener( 'click', function ( e ) {
			e.preventDefault();
			open( trigger );
		} );
	} );

	modal.querySelectorAll( '[data-cafw-pro-close]' ).forEach( function ( el ) {
		el.addEventListener( 'click', close );
	} );

	document.addEventListener( 'keydown', function ( e ) {
		if ( 'Escape' === e.key || 'Esc' === e.key ) {
			close();
		}
	} );
} )();
