/* global MBS_EarnMore, jQuery */
/**
 * @file assets/js/adminjs/admin-earn-more.js
 * Earn More (Affiliate) tab — Add My Store panel, favicon auto-fetch, live buy-button preview, and JSON serialisation.
 * @package MyBookShowroom
 * @since   1.0.0
 */
( function ( $ ) {
	'use strict';

	var s         = MBS_EarnMore.strings;
	var maxStores = parseInt( MBS_EarnMore.maxStores, 10 ) || 3;

	// Working copy of the stores array — kept in sync with the hidden textarea.
	var stores = Array.isArray( MBS_EarnMore.customStores ) ? MBS_EarnMore.customStores.slice() : [];

	// ── Helpers ───────────────────────────────────────────────────────────────

	function syncJson() {
		$( '#mbs_custom_stores_json' ).val( JSON.stringify( stores ) );
	}

	/* escHtml — use shared MBS_AdminUtils (mbs-admin-utils.js) */
	var escHtml = MBS_AdminUtils.escHtml;

	function findStoreIndex( storeId ) {
		for ( var i = 0; i < stores.length; i++ ) {
			if ( stores[ i ].id === storeId ) {
				return i;
			}
		}
		return -1;
	}

	function generateId( name ) {
		var slug = name.toLowerCase().replace( /[^a-z0-9]+/g, '-' ).replace( /^-|-$/g, '' ) || 'store';
		return slug + '-' + Date.now();
	}

	// ── Add-container: show button or max-reached message ─────────────────────

	function refreshAddContainer() {
		var $container = $( '#mbs-add-store-container' );
		if ( ! $container.length ) {
			return;
		}

		var $maxMsg = $container.find( '#mbs-max-stores-msg' );
		var $addBtn = $container.find( '#mbs-add-store-btn' );

		if ( stores.length >= maxStores ) {
			$addBtn.hide();
			if ( ! $maxMsg.length ) {
				$container.prepend(
					'<p class="description" id="mbs-max-stores-msg">' + escHtml( s.maxStoresMsg ) + '</p>'
				);
			} else {
				$maxMsg.show();
			}
		} else {
			$maxMsg.hide();
			$addBtn.show();
		}
	}

	// ── Build a store-row HTML string ─────────────────────────────────────────

	function buildStoreRowHtml( store ) {
		var storeId = escHtml( store.id );

		var html = '<div class="mbs-custom-store-row" data-store-id="' + storeId + '">';

		// Row header
		html += '<div class="mbs-store-row-header">';
		if ( store.favicon_url ) {
			html += '<img src="' + MBS_AdminUtils.escAttr( store.favicon_url ) + '" alt="" width="16" height="16" class="mbs-store-favicon">';
		}
		html += '<strong>' + escHtml( store.name ) + '</strong>';
		html += '<span class="mbs-store-url-preview">' + escHtml( store.url ) + '</span>';
		html += '<button type="button" class="button-link mbs-remove-store" data-store-id="' + storeId + '">' +
		        escHtml( s.removeBtnLabel ) + '</button>';
		html += '</div>';

		// Button preview
		html += '<div class="mbs-store-button-preview">';
		if ( store.favicon_url ) {
			html += '<img src="' + MBS_AdminUtils.escAttr( store.favicon_url ) + '" alt="" width="16" height="16">';
		}
		html += '<span>' + escHtml( store.name ) + '</span>';
		html += '<span class="mbs-btn-pill">' + escHtml( s.buyNow ) + '</span>';
		html += '</div>';

		html += '</div>';
		return html;
	}

	// ── Remove store ──────────────────────────────────────────────────────────

	$( document ).on( 'click', '.mbs-remove-store', function () {
		var storeId = $( this ).data( 'store-id' );
		var idx     = findStoreIndex( storeId );
		if ( idx !== -1 ) {
			stores.splice( idx, 1 );
		}
		$( this ).closest( '.mbs-custom-store-row' ).remove();
		syncJson();
		refreshAddContainer();
	} );

	// ── Show Add-Store form ───────────────────────────────────────────────────

	$( document ).on( 'click', '#mbs-add-store-btn', function () {
		$( this ).hide();
		$( '#mbs-store-error' ).hide().text( '' );
		$( '#mbs-add-store-form' ).slideDown( 200 );
	} );

	// ── Cancel Add-Store form ─────────────────────────────────────────────────

	$( document ).on( 'click', '#mbs-cancel-store-btn', function () {
		resetForm();
		$( '#mbs-add-store-form' ).slideUp( 200, function () {
			refreshAddContainer();
		} );
	} );

	function resetForm() {
		$( '#mbs_new_store_name' ).val( '' );
		$( '#mbs_new_store_url' ).val( '' );
		$( '#mbs_new_store_code' ).val( '' );
		$( '#mbs_new_store_pattern' ).val( '' );
		$( '#mbs_new_store_favicon_url' ).val( '' );
		$( '#mbs-favicon-status' ).text( '' );
		$( '#mbs-preview-store-name' ).text( s.storeName );
		$( '#mbs-preview-favicon-wrap' ).empty();
		$( '#mbs-store-error' ).hide().text( '' );
	}

	// ── Live preview — updates on name input ──────────────────────────────────

	$( document ).on( 'input', '#mbs_new_store_name', function () {
		var name = $( this ).val().trim() || s.storeName;
		$( '#mbs-preview-store-name' ).text( name );
	} );

	// ── Favicon fetch — triggered on URL blur ─────────────────────────────────

	var faviconTimer = null;

	$( document ).on( 'blur', '#mbs_new_store_url', function () {
		var url = $( this ).val().trim();
		if ( ! url ) {
			return;
		}

		$( '#mbs-favicon-status' ).text( s.fetchingFavicon );
		$( '#mbs_new_store_favicon_url' ).val( '' );
		$( '#mbs-preview-favicon-wrap' ).empty();

		clearTimeout( faviconTimer );
		faviconTimer = setTimeout( function () {
			$.post( MBS_EarnMore.ajaxUrl, {
				action:    'mbs_fetch_affiliate_favicon',
				nonce:     MBS_EarnMore.nonce,
				store_url: url,
			} )
			.done( function ( response ) {
				if ( response && response.success && response.data && response.data.favicon_url ) {
					var fav = response.data.favicon_url;
					$( '#mbs_new_store_favicon_url' ).val( fav );
					$( '#mbs-preview-favicon-wrap' ).html(
						'<img src="' + MBS_AdminUtils.escAttr( fav ) + '" width="16" height="16" alt="" style="vertical-align:middle;">'
					);
					$( '#mbs-favicon-status' ).text( '' );
				} else {
					$( '#mbs-favicon-status' ).text( s.noIconLabel );
				}
			} )
			.fail( function () {
				$( '#mbs-favicon-status' ).text( s.noIconLabel );
			} );
		}, 600 );
	} );

	// ── Save / Add store ──────────────────────────────────────────────────────

	$( document ).on( 'click', '#mbs-save-store-btn', function () {
		var name       = $( '#mbs_new_store_name' ).val().trim();
		var url        = $( '#mbs_new_store_url' ).val().trim();
		var code       = $( '#mbs_new_store_code' ).val().trim();
		var pattern    = $( '#mbs_new_store_pattern' ).val().trim();
		var faviconUrl = $( '#mbs_new_store_favicon_url' ).val();
		var $err       = $( '#mbs-store-error' );

		$err.hide().text( '' );

		// Validate
		if ( ! name ) {
			$err.text( s.nameRequired ).show();
			return;
		}
		if ( ! url ) {
			$err.text( s.urlRequired ).show();
			return;
		}
		if ( pattern && pattern.indexOf( '{CODE}' ) === -1 ) {
			$err.text( s.patternInvalid ).show();
			return;
		}
		if ( stores.length >= maxStores ) {
			$err.text( s.maxStoresMsg ).show();
			return;
		}

		var store = {
			id:          generateId( name ),
			name:        name.substring( 0, 50 ),
			url:         url,
			code:        code.substring( 0, 100 ),
			pattern:     pattern,
			favicon_url: faviconUrl,
		};

		stores.push( store );
		syncJson();

		// Append row to DOM
		$( '#mbs-custom-stores-list' ).append( buildStoreRowHtml( store ) );

		// Reset form and update container
		resetForm();
		$( '#mbs-add-store-form' ).slideUp( 200, function () {
			refreshAddContainer();
		} );
	} );

	// ── Init ──────────────────────────────────────────────────────────────────

	// Ensure hidden textarea is in sync on page load (covers the PHP-rendered stores).
	syncJson();

} )( jQuery );
