// Use the global uploadImageToWordPressMedia if available
jQuery( document ).ready( function ( $ ) {
	// Listen for external image selection and set the attribute of the alpha image block
	$( document ).on(
		'pexels:externalImageSelected',
		function ( e, imgHtml, blockId ) {
			// Try to find the selected block in the editor and set its attribute
			if ( window.wp && wp.data && wp.data.dispatch && blockId ) {
				var match = imgHtml.match( /src=["']([^"']+)["']/ );
				if ( match && match[ 1 ] ) {
					// Compose mediaImage object
					var mediaImage = {
						id: null, // No id from external source
						url: match[ 1 ],
						alt: '', // No alt from external source
					};
					wp.data
						.dispatch( 'core/block-editor' )
						.updateBlockAttributes( blockId, { mediaImage } );
					console.log(
						'Set alpha image block mediaImage:',
						mediaImage,
						'Block ID:',
						blockId
					);
				}
			}
		}
	);

	var PEXELS_API = 'JXdfZlHLSUKs2VKIARkcgBYm3OcJEiFO6pUQMjaKAHd3wUygetgEWahT';

	function isAlphaImageBlock() {
		var block = wp.data.select( 'core/block-editor' ).getSelectedBlock();
		var isAlphaImageBlock = block && block.name === 'alpha-blocks/image';
		return isAlphaImageBlock;
	}

	var l10n = wp.media.view.l10n;

	var frame = wp.media.view.MediaFrame.Select;
	// var originalOpen = frame.prototype.open;

	wp.media.view.MediaFrame.Select = frame.extend( {
		initialize: function () {
			frame.prototype.initialize.apply( this, arguments );

			var State = wp.media.controller.State.extend( {
				insert: function () {
					this.frame.close();
				},
			} );

			this.states.add( [
				new State( {
					id: 'alpha_search_image',
					search: false,
					title: 'Search Image',
				} ),
			] );

			// On render
			this.on(
				'content:render:alpha_search_image',
				this.renderMyTabContent,
				this
			);
		},
		browseRouter: function ( routerView ) {
			var Tabs = {
				upload: {
					text: l10n.uploadFilesTitle,
					priority: 20,
				},
				browse: {
					text: l10n.mediaLibraryTitle,
					priority: 40,
				},
				// alpha_search_image: {
				//   text: "Search Image",
				//   priority: 60
				// }
			};
			if ( isAlphaImageBlock() ) {
				Tabs[ 'alpha_search_image' ] = {
					text: 'Search Image',
					priority: 60,
				};
			} else {
				delete Tabs[ 'alpha_search_image' ];
			}
			routerView.set( Tabs );
		},
		// open: function() {
		//   originalOpen.apply(this, arguments);
		//   var block = wp.data.select('core/block-editor').getSelectedBlock();
		//   var isAlphaImageBlock = block && block.name === 'alphablock/image';

		//   this.$el.toggleClass('alphablock-image-selected', isAlphaImageBlock);
		// },
		renderMyTabContent: function () {
			var MyTabContent = wp.Backbone.View.extend( {
				tagName: 'div',
				className: 'my-tab-content',
				events: {
					'click .pexels-search-btn': 'onSearch',
					'change .pexels-filter-color': 'onFilterChange',
					'change .pexels-filter-orientation': 'onFilterChange',
				},
				render: function () {
					// Acceptable values from Pexels API docs
					var colorOptions = [
						'',
						'red',
						'orange',
						'yellow',
						'green',
						'turquoise',
						'blue',
						'violet',
						'pink',
						'brown',
						'black',
						'gray',
						'white',
					];
					var orientationOptions = [
						'',
						'landscape',
						'portrait',
						'square',
					];
					var colorSelect =
						'<label class="pexels-label">Color: <select class="pexels-filter-color attachment-filters">' +
						'<option value="">Any Color</option>' +
						colorOptions
							.slice( 1 )
							.map( function ( c ) {
								return (
									'<option value="' +
									c +
									'">' +
									c.charAt( 0 ).toUpperCase() +
									c.slice( 1 ) +
									'</option>'
								);
							} )
							.join( '' ) +
						'</select></label>';
					var orientationSelect =
						'<label class="pexels-label">Orientation: <select class="pexels-filter-orientation attachment-filters">' +
						'<option value="">Any Orientation</option>' +
						orientationOptions
							.slice( 1 )
							.map( function ( o ) {
								return (
									'<option value="' +
									o +
									'">' +
									o.charAt( 0 ).toUpperCase() +
									o.slice( 1 ) +
									'</option>'
								);
							} )
							.join( '' ) +
						'</select></label>';
					this.$el.html(
						'<div class="pexels-toolbar">' +
							'<div class="pexels-toolbar-left">' +
							colorSelect +
							orientationSelect +
							'</div>' +
							'<div class="pexels-toolbar-right">' +
							'<input type="search" class="pexels-search-input search" placeholder="Search images on Pexels..." /> ' +
							'<button class="pexels-search-btn button" disabled>Search</button>' +
							'</div>' +
							'</div>' +
							'<div class="attachments-browser">' +
							'<ul class="pexels-results"></ul>' +
							'<div class="pexels-pagination-wrapper">' +
							'<button class="pexels-pagination-prev button">Prev</button>' +
							'<span class="pexels-pagination-info"></span>' +
							'<button class="pexels-pagination-next button">Next</button>' +
							'</div>' +
							'</div>'
					);
					// Enable/disable search button based on input
					var $searchInput = this.$( '.pexels-search-input' );
					var $searchBtn = this.$( '.pexels-search-btn' );
					$searchInput.on( 'input', function () {
						if ( $searchInput.val().trim().length > 0 ) {
							$searchBtn.prop( 'disabled', false );
						} else {
							$searchBtn.prop( 'disabled', true );
						}
					} );
				},
				initialize: function () {
					this.render();
					this.page = 1;
					this.totalPages = 1;
					this.searchMode = false;
					this.loadDefaultImages( false, 1 );
					var self = this;
					this.$el.on(
						'click',
						'.pexels-pagination-prev',
						function () {
							if ( self.page > 1 ) {
								self.page--;
								if ( self.searchMode ) {
									// Replace images when going to previous page in search mode
									self.onSearchPage( false );
								} else {
									self.loadDefaultImages( false, self.page );
								}
							}
						}
					);
					this.$el.on(
						'click',
						'.pexels-pagination-next',
						function () {
							if ( self.page < self.totalPages ) {
								self.page++;
								if ( self.searchMode ) {
									// Append images when going to next page in search mode
									self.onSearchPage( true );
								} else {
									self.loadDefaultImages( true, self.page );
								}
							}
						}
					);
				},
				loadDefaultImages: function ( append, page ) {
					var self = this;
					var color = this.$( '.pexels-filter-color' ).val() || '';
					var orientation =
						this.$( '.pexels-filter-orientation' ).val() || '';
					var url = 'https://api.pexels.com/v1/curated?per_page=20';
					if ( color ) url += '&color=' + encodeURIComponent( color );
					if ( orientation )
						url +=
							'&orientation=' + encodeURIComponent( orientation );
					if ( page ) url += '&page=' + page;
					if ( ! append )
						self.$( '.pexels-results' ).html(
							'<li class="loading"><span class="spinner is-active" style="float:none;display:inline-block;vertical-align:middle;margin:40px auto;"></span></li>'
						);
					$.ajax( {
						url: url,
						headers: { Authorization: PEXELS_API },
						success: function ( data ) {
							var html = '';
							if ( data && data.photos && data.photos.length ) {
								data.photos.forEach( function ( photo ) {
									html +=
										'<li class="pexels-image-item-masonry">';
									html +=
										'<div class="pexels-image-wrapper">';
									html +=
										'<img src="' +
										photo.src.medium +
										'" data-full="' +
										photo.src.original +
										'" alt="' +
										( photo.alt || '' ) +
										'" class="pexels-img-thumb" />';
									html +=
										'<div class="pexels-image-caption-overlay">' +
										( photo.alt || '' ) +
										'</div>';
									html += '</div>';
									html +=
										'<div class="pexels-button-wrapper">';
									html +=
										'<button class="pexels-download-btn" data-url="' +
										photo.src.original +
										'" data-alt="' +
										( photo.alt || '' ) +
										'" title="Download & Add to Media">Download</button>';
									html +=
										'<button class="pexels-external-btn" data-url="' +
										photo.src.original +
										'" title="Use as External Image" style="margin-left:8px;">Use Externally</button>';
									html += '</div>';
									// html += '<div class="pexels-image-caption-bottom">' + (photo.alt || '') + '</div>';
									html += '</li>';
								} );
								self.totalPages = data.total_results
									? Math.ceil( data.total_results / 20 )
									: self.page;
							} else if ( ! append ) {
								html +=
									'<li><span>No images found.</span></li>';
								self.totalPages = 1;
							}
							if ( append ) {
								self.$( '.pexels-results' ).append( html );
							} else {
								self.$( '.pexels-results' ).html( html );
							}
							self.$( '.pexels-pagination-info' ).text(
								'Page ' + self.page + ' of ' + self.totalPages
							);
							self.loading = false;
						},
						error: function ( xhr ) {
							self.$( '.pexels-results' ).html(
								'<li><span>Error loading images.</span></li>'
							);
							self.$( '.pexels-pagination-info' ).text( '' );
							self.loading = false;
						},
					} );
				},
				onSearch: function () {
					var self = this;
					var query = this.$( '.pexels-search-input' ).val();
					var color = this.$( '.pexels-filter-color' ).val() || '';
					var orientation =
						this.$( '.pexels-filter-orientation' ).val() || '';
					self.searchMode = !! query;
					self.page = 1;
					var url;
					if ( ! query ) {
						self.loadDefaultImages( false, 1 );
						return;
					}
					url =
						'https://api.pexels.com/v1/search?query=' +
						encodeURIComponent( query ) +
						'&per_page=10';
					if ( color ) url += '&color=' + encodeURIComponent( color );
					if ( orientation )
						url +=
							'&orientation=' + encodeURIComponent( orientation );
					self.$( '.pexels-results' ).html(
						'<li class="loading"><span class="spinner is-active" style="float:none;display:inline-block;vertical-align:middle;margin:40px auto;"></span></li>'
					);
					$.ajax( {
						url: url + '&page=1',
						headers: { Authorization: PEXELS_API },
						success: function ( data ) {
							var html = '';
							if ( data && data.photos && data.photos.length ) {
								data.photos.forEach( function ( photo ) {
									html +=
										'<li class="pexels-image-item-masonry">';
									html +=
										'<div class="pexels-image-wrapper">';
									html +=
										'<img src="' +
										photo.src.medium +
										'" data-full="' +
										photo.src.original +
										'" alt="' +
										( photo.alt || '' ) +
										'" class="pexels-img-thumb" />';
									html +=
										'<div class="pexels-image-caption-overlay">' +
										( photo.alt || '' ) +
										'</div>';
									html += '</div>';
									html +=
										'<div class="pexels-button-wrapper">';
									html +=
										'<button class="pexels-download-btn" data-url="' +
										photo.src.original +
										'" data-alt="' +
										( photo.alt || '' ) +
										'" title="Download & Add to Media">Download</button>';
									html +=
										'<button class="pexels-external-btn" data-url="' +
										photo.src.original +
										'" title="Use as External Image" style="margin-left:8px;">Use Externally</button>';
									html += '</div>';

									// html += '<div class="pexels-image-caption-bottom">' + (photo.alt || '') + '</div>';
									html += '</li>';
								} );
								self.totalPages = data.total_results
									? Math.ceil( data.total_results / 10 )
									: self.page;
							} else {
								html +=
									'<li><span>No images found.</span></li>';
								self.totalPages = 1;
							}
							self.$( '.pexels-results' ).html( html );
							self.$( '.pexels-pagination-info' ).text(
								'Page ' + self.page + ' of ' + self.totalPages
							);
							self.loading = false;
						},
						error: function () {
							self.$( '.pexels-results' ).html(
								'<li><span>Error loading images.</span></li>'
							);
							self.$( '.pexels-pagination-info' ).text( '' );
							self.loading = false;
						},
					} );
				},
				onSearchPage: function ( append ) {
					var self = this;
					var query = this.$( '.pexels-search-input' ).val();
					var color = this.$( '.pexels-filter-color' ).val() || '';
					var orientation =
						this.$( '.pexels-filter-orientation' ).val() || '';
					var url =
						'https://api.pexels.com/v1/search?query=' +
						encodeURIComponent( query ) +
						'&per_page=10';
					if ( color ) url += '&color=' + encodeURIComponent( color );
					if ( orientation )
						url +=
							'&orientation=' + encodeURIComponent( orientation );
					url += '&page=' + self.page;
					if ( ! append )
						self.$( '.pexels-results' ).html(
							'<li class="loading"><span class="spinner is-active" style="float:none;display:inline-block;vertical-align:middle;margin:40px auto;"></span></li>'
						);
					$.ajax( {
						url: url,
						headers: { Authorization: PEXELS_API },
						success: function ( data ) {
							var html = '';
							if ( data && data.photos && data.photos.length ) {
								data.photos.forEach( function ( photo ) {
									html +=
										'<li class="pexels-image-item-masonry">';
									html +=
										'<div class="pexels-image-wrapper">';
									html +=
										'<img src="' +
										photo.src.medium +
										'" data-full="' +
										photo.src.original +
										'" alt="' +
										( photo.alt || '' ) +
										'" class="pexels-img-thumb" />';
									html +=
										'<div class="pexels-image-caption-overlay">' +
										( photo.alt || '' ) +
										'</div>';
									html += '</div>';
									html +=
										'<div class="pexels-button-wrapper">';
									html +=
										'<button class="pexels-download-btn" data-url="' +
										photo.src.original +
										'" data-alt="' +
										( photo.alt || '' ) +
										'" title="Download & Add to Media">Download</button>';
									html +=
										'<button class="pexels-external-btn" data-url="' +
										photo.src.original +
										'" title="Use as External Image" style="margin-left:8px;">Use Externally</button>';
									html += '</div>';
									// html += '<div class="pexels-image-caption-bottom">' + (photo.alt || '') + '</div>';
									html += '</li>';
								} );
								self.totalPages = data.total_results
									? Math.ceil( data.total_results / 10 )
									: self.page;
							} else {
								html +=
									'<li><span>No images found.</span></li>';
								self.totalPages = 1;
							}
							if ( append ) {
								self.$( '.pexels-results' ).append( html );
							} else {
								self.$( '.pexels-results' ).html( html );
							}
							self.$( '.pexels-pagination-info' ).text(
								'Page ' + self.page + ' of ' + self.totalPages
							);
							self.loading = false;
						},
						error: function () {
							self.$( '.pexels-results' ).html(
								'<li><span>Error loading images.</span></li>'
							);
							self.$( '.pexels-pagination-info' ).text( '' );
							self.loading = false;
						},
					} );
				},

				// Infinite scroll
				events: {
					'click .pexels-search-btn': 'onSearch',
					'change .pexels-filter-color': 'onFilterChange',
					'change .pexels-filter-orientation': 'onFilterChange',
					'scroll .attachments-browser': 'onScroll',
					'click .pexels-download-btn': 'onDownload',
					'click .pexels-external-btn': 'onExternalBtn',
				},
				onExternalBtn: function ( e ) {
					e.preventDefault();
					var url = $( e.currentTarget ).data( 'url' );
					// Format as <img src="..." />
					var imgHtml =
						'<img src="' + url + '" alt="Pexels Image" />';
					var blockId = null;
					if ( window.wp && wp.data && wp.data.select ) {
						var block = wp.data
							.select( 'core/block-editor' )
							.getSelectedBlock();
						if ( block && block.clientId ) {
							blockId = block.clientId;
						}
					}
					// Trigger a custom event with the HTML and blockId
					$( document ).trigger( 'pexels:externalImageSelected', [
						imgHtml,
						blockId,
					] );
					// Try to close the media modal
					if ( window.wp && wp.media && wp.media.frame ) {
						try {
							wp.media.frame.close();
						} catch ( e ) {}
					} else {
						// Try to close any open thickbox/modal
						if ( window.tb_remove ) tb_remove();
					}
					// Log the response
					console.log(
						'External image HTML sent to post:',
						imgHtml,
						'Block ID:',
						blockId
					);
				},
				onDownload: function ( e ) {
					e.preventDefault();
					var $btn = $( e.currentTarget );
					var imageUrl = $btn.data( 'url' );
					var imageAlt = $btn.data( 'alt' ) || '';
					$btn.prop( 'disabled', true ).text( 'Uploading...' );
					fetch( imageUrl )
						.then( function ( response ) {
							return response.blob();
						} )
						.then( function ( blob ) {
							var filename =
								'pexels-' +
								Date.now() +
								'.' +
								( blob.type.split( '/' )[ 1 ] || 'jpg' );
							if (
								typeof uploadImageToWordPressMedia ===
									'function' &&
								typeof alpbUploadImage !== 'undefined'
							) {
								uploadImageToWordPressMedia(
									blob,
									filename,
									alpbUploadImage.nonce,
									function ( data ) {
										if (
											data &&
											data.success &&
											data.data &&
											data.data.id
										) {
											$btn.text( 'Added!' );
										} else {
											$btn.text( 'Failed' );
											alert( 'Upload failed.' );
											if (
												data &&
												data.data &&
												data.data.message
											) {
												console.log(
													'Upload failed:',
													data.data.message
												);
											} else {
												console.log(
													'Upload failed:',
													data
												);
											}
										}
										setTimeout( function () {
											$btn.prop( 'disabled', false ).text(
												'Download'
											);
										}, 2000 );
									}
								);
							} else {
								$btn.text( 'Failed' );
								setTimeout( function () {
									$btn.prop( 'disabled', false ).text(
										'Download'
									);
								}, 2000 );
								alert( 'Upload function not available.' );
							}
						} )
						.catch( function ( error ) {
							$btn.text( 'Failed' );
							setTimeout( function () {
								$btn.prop( 'disabled', false ).text(
									'Download'
								);
							}, 2000 );
							console.log( 'Upload failed:', error );
						} );
				},
				onScroll: function ( e ) {
					var self = this;
					var $el = $( e.currentTarget );
					if ( self.loading ) return;
					var scrollBottom =
						$el[ 0 ].scrollTop + $el[ 0 ].clientHeight;
					var scrollHeight = $el[ 0 ].scrollHeight;
					if ( scrollBottom + 50 >= scrollHeight ) {
						self.loading = true;
						self.page = ( self.page || 1 ) + 1;
						if ( self.searchMode ) {
							// Search mode
							var query = self.$( '.pexels-search-input' ).val();
							var color =
								self.$( '.pexels-filter-color' ).val() || '';
							var orientation =
								self.$( '.pexels-filter-orientation' ).val() ||
								'';
							var url =
								'https://api.pexels.com/v1/search?query=' +
								encodeURIComponent( query ) +
								'&per_page=10';
							if ( color )
								url += '&color=' + encodeURIComponent( color );
							if ( orientation )
								url +=
									'&orientation=' +
									encodeURIComponent( orientation );
							url += '&page=' + self.page;
							$.ajax( {
								url: url,
								headers: { Authorization: PEXELS_API },
								success: function ( data ) {
									var html = '';
									if (
										data &&
										data.photos &&
										data.photos.length
									) {
										data.photos.forEach(
											function ( photo ) {
												html +=
													'<li class="rounded overflow-hidden shadow bg-white flex flex-col items-center min-w-[200px]" style="min-width:200px;">';
												html +=
													'<img src="' +
													photo.src.medium +
													'" data-full="' +
													photo.src.original +
													'" alt="' +
													( photo.alt || '' ) +
													'" class="pexels-img-thumb w-full object-cover cursor-pointer" style="min-width:200px;max-width:100%;" />';
												html +=
													'<div class="text-xs text-gray-700 truncate w-full px-2 py-1">' +
													( photo.alt || '' ) +
													'</div>';
												html += '</li>';
											}
										);
									}
									self.$( '.pexels-results' ).append( html );
									self.loading = false;
								},
								error: function () {
									self.loading = false;
								},
							} );
						} else {
							// Default mode
							self.loadDefaultImages( true, self.page );
						}
					}
				},
			} );

			var view = new MyTabContent();

			if ( isAlphaImageBlock() ) {
				this.content.set( view );
			}
		},
	} );

	// Add the custom template to the page (not used, UI is rendered by JS)
} );
