/**
 * @file assets/js/adminjs/repeater/mbs-link-icon-helper.js
 * MBS.LinkIconHelper -- Shared retailer/platform icon and label helper.
 *
 * Combined 19-entry LINK_DOMAINS map, detectKey(), applyDetection(),
 * updateIconPreview(), and resetIconToSiteIcon().
 *
 * Consumed by: mbs-buy-links.js, mbs-reader-platforms.js, mbs-format-buy-links.js.
 * Must be enqueued before all three callers (after mbs-contributors in
 * $repeater_modules array in class-mbs-admin-assets.php).
 *
 * @package MyBookShowroom
 * @since   1.5.0
 */

// =============================================================================
// Link Icon Helper
// =============================================================================

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

	/**
	 * Combined 19-entry domain map.
	 * Mirrors PHP MBS_Metabox_Buy_Links::detect_retailer_key() (16 entries)
	 * plus scribd, librarything, and reedsy which PHP does not detect
	 * (intentional gap -- JS detection fills the hidden retailer key input).
	 */
	var LINK_DOMAINS = [
		{ domain: 'amazon.com',        key: 'amazon',       label: __( 'Amazon', 'my-book-showroom' ) },
		{ domain: 'barnesandnoble.com', key: 'bn',           label: __( 'Barnes & Noble', 'my-book-showroom' ) },
		{ domain: 'booksamillion.com',  key: 'bam',          label: __( 'Books-A-Million', 'my-book-showroom' ) },
		{ domain: 'bookshop.org',       key: 'bookshop',     label: __( 'Bookshop.org', 'my-book-showroom' ) },
		{ domain: 'kobo.com',           key: 'kobo',         label: __( 'Kobo', 'my-book-showroom' ) },
		{ domain: 'google.com',         key: 'google',       label: __( 'Google Play', 'my-book-showroom' ) },
		{ domain: 'apple.com',          key: 'apple',        label: __( 'Apple Books', 'my-book-showroom' ) },
		{ domain: 'audible.com',        key: 'audible',      label: __( 'Audible', 'my-book-showroom' ) },
		{ domain: 'waterstones.com',    key: 'waterstones',  label: __( 'Waterstones', 'my-book-showroom' ) },
		{ domain: 'powells.com',        key: 'powells',      label: __( "Powell's", 'my-book-showroom' ) },
		{ domain: 'gumroad.com',        key: 'gumroad',      label: __( 'Gumroad', 'my-book-showroom' ) },
		{ domain: 'bookfunnel.com',     key: 'bookfunnel',   label: __( 'BookFunnel', 'my-book-showroom' ) },
		{ domain: 'myshopify.com',      key: 'shopify-buy',  label: __( 'Shopify', 'my-book-showroom' ) },
		{ domain: 'goodreads.com',      key: 'goodreads',    label: __( 'Goodreads', 'my-book-showroom' ) },
		{ domain: 'bookbub.com',        key: 'bookbub',      label: __( 'BookBub', 'my-book-showroom' ) },
		{ domain: 'thestorygraph.com',  key: 'storygraph',   label: __( 'StoryGraph', 'my-book-showroom' ) },
		{ domain: 'scribd.com',         key: 'scribd',       label: __( 'Scribd', 'my-book-showroom' ) },
		{ domain: 'librarything.com',   key: 'librarything', label: __( 'LibraryThing', 'my-book-showroom' ) },
		{ domain: 'reedsy.com',         key: 'reedsy',       label: __( 'Reedsy', 'my-book-showroom' ) }
	];

	MBS.LinkIconHelper = {

		/**
		 * Detect retailer/platform key from a URL string.
		 *
		 * @param  {string}      url  Full URL.
		 * @returns {Object|null}     { key, label } or null if unrecognized.
		 */
		detectKey: function( url ) {
			if ( ! url ) { return null; }
			var host = '';
			try {
				host = ( new URL( url ) ).hostname.toLowerCase();
			} catch ( ex ) {
				return null;
			}
			for ( var i = 0; i < LINK_DOMAINS.length; i++ ) {
				var entry = LINK_DOMAINS[ i ];
				if ( host === entry.domain || host.slice( -( entry.domain.length + 1 ) ) === '.' + entry.domain ) {
					return { key: entry.key, label: entry.label };
				}
			}
			return null;
		},

		/**
		 * Apply URL detection to a repeater row.
		 *
		 * Detects the retailer/platform key from url, fills label when empty,
		 * and updates the icon preview. Clears key and resets icon when undetected.
		 *
		 * @param  {jQuery} $row         The row element.
		 * @param  {string} url          URL to detect from.
		 * @param  {string} retailersUrl Base URL for retailer SVG icons.
		 * @param  {string} siteIconUrl  Fallback site icon URL.
		 * @param  {string} defaultLabel Default label for the label field ('Buy Now' for buy links, '' for platforms).
		 * @returns {void}
		 */
		applyDetection: function( $row, url, retailersUrl, siteIconUrl, defaultLabel ) {
			var self     = MBS.LinkIconHelper;
			var detected = self.detectKey( url );

			if ( detected ) {
				// Set hidden key field (dual selector covers both buy-link and platform rows).
				$row.find( '.mbs-buy-link-retailer-key, .mbs-platform-retailer-key' ).val( detected.key );

				// Fill label only when currently empty -- never overwrite user input. (A4-001)
				var $labelField = $row.find( '.mbs-buy-link-label, .mbs-platform-label' );
				if ( '' === $.trim( $labelField.val() ) ) {
					$labelField.val( detected.label );
				}

				self.updateIconPreview( $row.find( '.mbs-buy-link-icon-wrap' ), detected.key, retailersUrl );
			} else {
				// Clear hidden key fields (dual selector -- A4-006).
				$row.find( '.mbs-buy-link-retailer-key, .mbs-platform-retailer-key' ).val( '' );
				self.resetIconToSiteIcon( $row.find( '.mbs-buy-link-icon-wrap' ), siteIconUrl );
			}
		},

		/**
		 * Update the icon preview img to the branded SVG for a known key.
		 *
		 * All buy-link and platform rows share the same CSS classes after A2-001
		 * class-name alignment -- no dual selectors needed here.
		 *
		 * @param  {jQuery} $iconWrap    The .mbs-buy-link-icon-wrap element.
		 * @param  {string} key          Retailer/platform key.
		 * @param  {string} retailersUrl Base URL for retailer SVG icons.
		 * @returns {void}
		 */
		updateIconPreview: function( $iconWrap, key, retailersUrl ) {
			if ( ! key || ! retailersUrl ) { return; }
			var $img = $iconWrap.find( '.mbs-buy-link-icon-preview' );
			if ( ! $img.length ) {
				$img = $( '<img>' ).attr( { width: 24, height: 24, alt: '' } ).addClass( 'mbs-buy-link-icon-preview' );
				$iconWrap.empty().append( $img );
			}
			$img.attr( 'src', retailersUrl + key + '.svg' ).show();
			$iconWrap.find( '.mbs-buy-link-icon-placeholder' ).hide();
		},

		/**
		 * Reset the icon preview to the site icon (or placeholder) for unknown URLs.
		 *
		 * @param  {jQuery} $iconWrap   The .mbs-buy-link-icon-wrap element.
		 * @param  {string} siteIconUrl Site icon URL, or empty string.
		 * @returns {void}
		 */
		resetIconToSiteIcon: function( $iconWrap, siteIconUrl ) {
			var $img = $iconWrap.find( '.mbs-buy-link-icon-preview' );
			if ( siteIconUrl ) {
				if ( ! $img.length ) {
					$img = $( '<img>' ).attr( { width: 24, height: 24, alt: '' } ).addClass( 'mbs-buy-link-icon-preview' );
					$iconWrap.empty().append( $img );
				}
				$img.attr( 'src', siteIconUrl ).show();
			} else {
				$img.hide();
				if ( ! $iconWrap.find( '.mbs-buy-link-icon-placeholder' ).length ) {
					$iconWrap.empty().append( $( '<span>' ).addClass( 'mbs-buy-link-icon-placeholder' ).css( { display: 'inline-block', width: '24px', height: '24px', background: '#ddd', borderRadius: '4px' } ) );
				}
			}
		}

	};

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