/**
 * @file assets/js/mbs-front-buy-links.js
 * Rebuilds #mbs-buy-links when the user switches format tabs.
 *
 * Listens to mbs:format:changed (fired by mbs-format-tabs.js) and replaces
 * the button children of #mbs-buy-links from fmt.buy_links.
 * Falls back to data-fallback-url when the format has no buy links.
 * Uses DOM construction throughout -- never innerHTML or .html() (F-003).
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

/* global jQuery */

( function( MBS, $, undefined ) {
	'use strict';
	var __ = wp.i18n.__;
	var sprintf = wp.i18n.sprintf;

	/**
	 * Format-tab buy link switcher.
	 *
	 * @namespace MBS.BuyLinks
	 */
	MBS.BuyLinks = {

		/** Retailer key to display label map (mirrors PHP get_retailer_label()). */
		labels: {
			amazon:         __( 'Amazon', 'my-book-showroom' ),
			apple:          __( 'Apple Books', 'my-book-showroom' ),
			audible:        __( 'Audible', 'my-book-showroom' ),
			bam:            __( 'Books-A-Million', 'my-book-showroom' ),
			bn:             __( 'Barnes & Noble', 'my-book-showroom' ),
			bookshop:       __( 'Bookshop.org', 'my-book-showroom' ),
			google:         __( 'Google Play', 'my-book-showroom' ),
			kobo:           __( 'Kobo', 'my-book-showroom' ),
			powells:        __( "Powell's", 'my-book-showroom' ),
			waterstones:    __( 'Waterstones', 'my-book-showroom' ),
			gumroad:        __( 'Gumroad', 'my-book-showroom' ),
			bookfunnel:     __( 'BookFunnel', 'my-book-showroom' ),
			'shopify-buy':  __( 'Shopify', 'my-book-showroom' ),
			'signed-copy':  __( 'Signed Copy', 'my-book-showroom' ),
			library:        __( 'Library', 'my-book-showroom' ),
			bookbub:        __( 'BookBub', 'my-book-showroom' ),
			goodreads:      __( 'Goodreads', 'my-book-showroom' ),
			storygraph:     __( 'StoryGraph', 'my-book-showroom' )
		},

		/**
		 * Resolve a human-readable label for a retailer key.
		 *
		 * @param {string} key Retailer key.
		 * @returns {string} Display label.
		 */
		getLabel: function( key ) {
			if ( ! key ) { return __( 'Buy Now', 'my-book-showroom' ); }
			return MBS.BuyLinks.labels[ key ] || ( key.charAt( 0 ).toUpperCase() + key.slice( 1 ) );
		},

		/**
		 * Build a single retailer anchor element.
		 *
		 * @param  {string} url          Destination URL.
		 * @param  {string} key          Retailer key (may be empty for custom links).
		 * @param  {string} retailersUrl Base URL for retailer PNG images.
		 * @param  {string} linkLabel    Custom label override (may be empty).
		 * @param  {string} siteIconUrl  Site icon URL for keyless links (may be empty).
		 * @return {HTMLElement}
		 */
		buildButton: function( url, key, retailersUrl, linkLabel, siteIconUrl ) {
			var label   = linkLabel || MBS.BuyLinks.getLabel( key );
			var safeKey = key || 'custom';
			var a       = document.createElement( 'a' );
			a.href      = url;
			a.className = 'mbs-retailer-btn mbs-retailer-' + safeKey;
			if ( key === 'gumroad' ) { a.classList.add( 'gumroad-button' ); }
			a.target    = '_blank';
			a.rel       = 'noopener noreferrer';
			a.setAttribute( 'aria-label', sprintf( __( '%s \u2014 Buy Now', 'my-book-showroom' ), label ) );
			if ( key && retailersUrl ) {
				var img       = document.createElement( 'img' );
				img.src       = retailersUrl + key + '.svg';
				img.alt       = '';
				img.setAttribute( 'aria-hidden', 'true' );
				img.className = 'mbs-retailer-logo';
				img.width     = 24;
				img.height    = 24;
				a.appendChild( img );
			} else if ( siteIconUrl ) {
				// F-3: site-icon fallback for custom / keyless links.
				var siteImg       = document.createElement( 'img' );
				siteImg.src       = siteIconUrl;
				siteImg.alt       = '';
				siteImg.setAttribute( 'aria-hidden', 'true' );
				siteImg.className = 'mbs-retailer-logo';
				siteImg.width     = 24;
				siteImg.height    = 24;
				a.appendChild( siteImg );
			}
			var labelSpan         = document.createElement( 'span' );
			labelSpan.className   = 'mbs-retailer-label';
			labelSpan.textContent = label;
			a.appendChild( labelSpan );
			return a;
		},

		/**
		 * Bind the mbs:format:changed event listener.
		 *
		 * @return {void}
		 */
		init: function() {
			$( document ).on( 'mbs:format:changed', function( e, fmt ) {
				var container = document.getElementById( 'mbs-buy-links' );
				if ( ! container ) { return; }

				var retailersUrl = container.getAttribute( 'data-retailers-url' ) || '';
				var fallbackUrl  = container.getAttribute( 'data-fallback-url' )  || '';
				var siteIconUrl  = container.getAttribute( 'data-site-icon-url' ) || '';
				var links        = ( fmt && Array.isArray( fmt.buy_links ) ) ? fmt.buy_links : [];

				// Clear existing buttons.
				while ( container.firstChild ) {
					container.removeChild( container.firstChild );
				}

				if ( links.length > 0 ) {
					container.classList.remove( 'mbs-buy-links-fallback' );
					links.forEach( function( link ) {
						var btn = MBS.BuyLinks.buildButton(
							link.url,
							link.retailer_key || '',
							retailersUrl,
							link.link_label || '',
							siteIconUrl
						);
						container.appendChild( btn );
					} );
				} else if ( fallbackUrl ) {
					// No per-format links -- fall back to purchase_link_text URL.
					container.classList.add( 'mbs-buy-links-fallback' );
					var btn = MBS.BuyLinks.buildButton( fallbackUrl, '', retailersUrl, '', siteIconUrl );
					container.appendChild( btn );
				}
				// If neither, container stays empty.
			} );
		}
	};

	MBS.register( function() {
		MBS.BuyLinks.init();
	} );

} )( window.MBS = window.MBS || {}, jQuery );
