/**
 * @file assets/js/mbs-layout-popup.js
 * Popup Layout modal interaction (PRO); DOM construction only, no innerHTML injection.
 * @package MyBookShowroom
 * @since   1.0.0
 */

/* global jQuery, MBS_Popup */

( function( $ ) {
	'use strict';

	const { __ } = wp.i18n;

	/**
	 * Populate an open popup modal from the structured data-book payload.
	 *
	 * @param {HTMLElement} modal  The modal element to populate.
	 * @param {Object}      book   Structured book data from data-book attribute.
	 * @return {void}
	 */
	function populateModal( modal, book ) {

		// Title
		$( modal ).find( '.mbs-popup-book-title' ).text( book.title || '' );

		// Author
		$( modal ).find( '.mbs-popup-author' ).text( book.author || '' );

		// Meta (publisher + date)
		var meta = [ book.publisher, book.pub_date ].filter( Boolean ).join( ' \u2022 ' );
		$( modal ).find( '.mbs-popup-meta' ).text( meta );

		// Teaser
		$( modal ).find( '.mbs-popup-teaser' ).text( book.teaser || '' );

		// Formats list — DOM construction, no innerHTML
		var $formatsList = $( modal ).find( '.mbs-popup-formats' ).empty();
		if ( book.formats && book.formats.length ) {
			$.each( book.formats, function( i, fmt ) {
				var li       = document.createElement( 'li' );
				li.textContent = fmt.price
					? fmt.format + ' \u2014 ' + fmt.price
					: fmt.format;
				$formatsList.append( li );
			} );
		}

		// Cover image — DOM construction, no innerHTML
		var $coverSlot = $( modal ).find( '.mbs-popup-cover' ).empty();
		if ( book.cover_url ) {
			var img = document.createElement( 'img' );
			img.src       = book.cover_url;
			img.alt       = book.cover_alt || book.title || '';
			img.className = 'mbs-popup-cover-img';
			$coverSlot.append( img );
		}

		// Buy links — DOM construction, no innerHTML
		var buyNowLabel = __( 'Buy Now', 'my-book-showroom' );
		var $buyLinks = $( modal ).find( '.mbs-popup-buy-links' ).empty();
		if ( book.buy_links && book.buy_links.length ) {
			$.each( book.buy_links, function( i, link ) {
				var a         = document.createElement( 'a' );
				a.href        = ( link.url && ! /^javascript:/i.test( link.url ) ) ? link.url : '#'; // FJ-001: block javascript: protocol
				a.textContent = link.label || buyNowLabel;
				a.className   = 'mbs-retailer-btn button button-primary';
				a.target      = '_blank';
				a.rel         = 'noopener';
				$buyLinks.append( a );
			} );
		}

		// Full-page link — FJ-001: block javascript: protocol before setting href.
		var safeFullLink = ( book.link && ! /^javascript:/i.test( book.link ) ) ? book.link : '#';
		$( modal ).find( '.mbs-popup-full-link' ).attr( 'href', safeFullLink );
	}

	/**
	 * Open the popup modal, populate it, and set up focus trap.
	 *
	 * @param {jQuery}      $trigger  The clicked trigger button.
	 * @param {HTMLElement} modal     The modal element to open.
	 * @param {Object}      book      Structured book data.
	 * @return {void}
	 */
	function openPopup( $trigger, modal, book ) {
		populateModal( modal, book );

		$( modal ).removeAttr( 'hidden' );

		var $modal     = $( modal );
		var $focusable = $modal.find( 'a[href], button, [tabindex]:not([tabindex="-1"])' );
		var $close     = $modal.find( '.mbs-popup-close' );

		$close.trigger( 'focus' );

		function closePopup() {
			$modal.attr( 'hidden', '' );
			$( document ).off( 'keydown.mbs-popup-' + modal.id );
			$trigger.trigger( 'focus' );
		}

		$modal.find( '.mbs-popup-close' ).off( 'click.mbs-popup' ).on( 'click.mbs-popup', closePopup );
		$modal.find( '.mbs-popup-overlay' ).off( 'click.mbs-popup' ).on( 'click.mbs-popup', closePopup );

		$( document ).off( 'keydown.mbs-popup-' + modal.id )
			.on( 'keydown.mbs-popup-' + modal.id, function( e ) {
				if ( ! $modal.is( ':visible' ) && $modal.attr( 'hidden' ) !== undefined ) {
					return;
				}

				if ( e.key === 'Escape' ) {
					closePopup();
					return;
				}

				if ( e.key === 'Tab' ) {
					$focusable = $modal.find( 'a[href], button, [tabindex]:not([tabindex="-1"])' ).filter( ':visible' );
					var $first = $focusable.first();
					var $last  = $focusable.last();

					if ( e.shiftKey ) {
						if ( document.activeElement === $first[ 0 ] ) {
							e.preventDefault();
							$last.trigger( 'focus' );
						}
					} else {
						if ( document.activeElement === $last[ 0 ] ) {
							e.preventDefault();
							$first.trigger( 'focus' );
						}
					}
				}
			} );
	}

	// ── Event delegation: one handler for all popup triggers on page ──────────
	$( document ).on( 'click', '.mbs-popup-trigger', function() {
		var $trigger = $( this );
		var modalId  = $trigger.data( 'popup-id' );
		var bookData = $trigger.data( 'book' );
		var modal    = document.getElementById( modalId );

		if ( ! modal || ! bookData ) {
			return;
		}

		openPopup( $trigger, modal, bookData );
	} );

} )( jQuery );
