/**
 * Variations Gallery Module - Admin Script
 *
 * @package OM_Product_Page_Essentials
 */

(function($) {
	'use strict';

	var __ = ( window.wp && window.wp.i18n && window.wp.i18n.__ ) ? window.wp.i18n.__ : function (s) { return s; };
	var _x = ( window.wp && window.wp.i18n && window.wp.i18n._x ) ? window.wp.i18n._x : function (s) { return s; };
	var _n = ( window.wp && window.wp.i18n && window.wp.i18n._n ) ? window.wp.i18n._n : function (s, p, n) { return n === 1 ? s : p; };
	var _sprintf = ( window.wp && window.wp.i18n && window.wp.i18n.sprintf ) ? window.wp.i18n.sprintf : function (s) { return s; };

	var OMPPEVariationsGalleryAdmin = {
		popup: null,
		currentLoop: null,
		editingItem: null,

		/**
		 * Initialize admin functionality.
		 */
		init: function() {
			var self = this;

			// Make gallery sortable
			$(document).on('woocommerce_variations_loaded', function() {
				self.initSortable();
			});

			// Initialize on page load for existing variations
			self.initSortable();

			// Add media button
			$(document).on('click', '.om-ppe-add-media', function(e) {
				e.preventDefault();
				self.openMediaLibrary($(this));
			});

			// Add video URL button
			$(document).on('click', '.om-ppe-add-video-url', function(e) {
				e.preventDefault();
				self.openVideoPopup($(this).data('loop'));
			});

			// Remove item
			$(document).on('click', '.om-ppe-remove-item', function(e) {
				e.preventDefault();
				var $variation = $(this).closest('.woocommerce_variation');
				$(this).closest('li').remove();

				// Trigger WooCommerce change detection
				$variation.addClass('variation-needs-update');
				$('button.cancel-variation-changes, button.save-variation-changes').prop('disabled', false);
				$('#woocommerce-product-data').trigger('woocommerce_variations_input_changed');
			});

			// Edit video URL
			$(document).on('click', '.om-ppe-video-url-thumbnail figure', function(e) {
				e.preventDefault();
				var $item = $(this).closest('li');
				self.editVideoItem($item);
			});

			// Popup close
			$(document).on('click', '.om-ppe-video-url-popup-close', function(e) {
				e.preventDefault();
				self.closeVideoPopup();
			});

			// Popup add/update
			$(document).on('click', '.om-ppe-video-url-popup-add', function(e) {
				e.preventDefault();
				self.addVideoFromPopup();
			});

			// Close popup on escape
			$(document).on('keyup', function(e) {
				if (e.key === 'Escape' && self.popup && self.popup.is(':visible')) {
					self.closeVideoPopup();
				}
			});

			// Close popup on background click
			$(document).on('click', '.om-ppe-video-url-popup', function(e) {
				if (e.target === this) {
					self.closeVideoPopup();
				}
			});
		},

		/**
		 * Initialize sortable galleries.
		 */
		initSortable: function() {
			$('.om-ppe-variation-gallery-sortable').sortable({
				placeholder: 'ui-sortable-placeholder',
				cursor: 'move',
				opacity: 0.65,
				update: function(event, ui) {
					// Trigger WooCommerce change detection when reordering
					var $variation = $(this).closest('.woocommerce_variation');
					$variation.addClass('variation-needs-update');
					$('button.cancel-variation-changes, button.save-variation-changes').prop('disabled', false);
					$('#woocommerce-product-data').trigger('woocommerce_variations_input_changed');
				}
			});
		},

		/**
		 * Open media library.
		 *
		 * @param {jQuery} $button Clicked button.
		 */
		openMediaLibrary: function($button) {
			var self = this;
			var loop = $button.data('loop');
			var $gallery = $button.closest('.om-ppe-variation-gallery');
			var $sortable = $gallery.find('.om-ppe-variation-gallery-sortable');

			// Debug logging
			console.log('OM PPE: Opening media library for loop:', loop);
			console.log('OM PPE: Gallery container found:', $gallery.length > 0);
			console.log('OM PPE: Sortable container found:', $sortable.length > 0);

			// Check if wp.media is available
			if (typeof wp === 'undefined' || typeof wp.media === 'undefined') {
				console.error('OM PPE Variations Gallery: wp.media is not available. Make sure the media library is enqueued.');
				alert( __( 'Media library is not available. Please refresh the page and try again.', 'ai-eshop-optimizer' ) );
				return;
			}

			// Check if sortable container exists
			if ($sortable.length === 0) {
				console.error('OM PPE Variations Gallery: Sortable container not found.');
				alert( __( 'Gallery container not found. Please refresh the page and try again.', 'ai-eshop-optimizer' ) );
				return;
			}

			var frame = wp.media({
				title: typeof omPPEVariationsGallery !== 'undefined' ? omPPEVariationsGallery.addToGallery : __( 'Add to gallery', 'ai-eshop-optimizer' ),
				button: {
					text: typeof omPPEVariationsGallery !== 'undefined' ? omPPEVariationsGallery.addToGallery : __( 'Add to gallery', 'ai-eshop-optimizer' )
				},
				multiple: true,
				library: {
					type: ['image', 'video']
				}
			});

			frame.on('select', function() {
				console.log('OM PPE: Media selected');
				var selection = frame.state().get('selection');

				selection.each(function(attachment) {
					var attachmentData = attachment.toJSON();
					var $item;

					console.log('OM PPE: Processing attachment:', attachmentData.id, attachmentData.type);

					if (attachmentData.type === 'video') {
						// Video attachment
						var placeholder = typeof omPPEVariationsGallery !== 'undefined' ? omPPEVariationsGallery.placeholderVideoUrl : '';

						$item = $('<li class="om-ppe-video-thumbnail">');
						$item.append('<figure><img src="' + placeholder + '" alt="" /></figure>');
						$item.append('<span class="om-ppe-remove-item dashicons dashicons-no"></span>');
						$item.append('<input type="hidden" name="botiga_variation_gallery[' + loop + '][]" value="' + attachmentData.id + '" />');
					} else {
						// Image attachment
						var thumb = attachmentData.sizes && attachmentData.sizes.thumbnail
							? attachmentData.sizes.thumbnail.url
							: attachmentData.url;

						$item = $('<li>');
						$item.append('<figure><img src="' + thumb + '" alt="" /></figure>');
						$item.append('<span class="om-ppe-remove-item dashicons dashicons-no"></span>');
						$item.append('<input type="hidden" name="botiga_variation_gallery[' + loop + '][]" value="' + attachmentData.id + '" />');
					}

					$sortable.append($item);
					console.log('OM PPE: Item appended to gallery');
				});

				// Trigger WooCommerce change detection to enable Save Changes button
				$sortable.closest('.woocommerce_variation').addClass('variation-needs-update');
				$('button.cancel-variation-changes, button.save-variation-changes').prop('disabled', false);
				$('#woocommerce-product-data').trigger('woocommerce_variations_input_changed');
			});

			frame.open();
		},

		/**
		 * Open video URL popup.
		 *
		 * @param {number} loop Variation loop index.
		 */
		openVideoPopup: function(loop) {
			this.currentLoop = loop;
			this.editingItem = null;
			this.popup = $('.om-ppe-video-url-popup');

			// Reset form
			this.popup.find('#om-ppe-video-url').val('');
			this.popup.find('#om-ppe-video-title').val('');
			this.popup.find('#om-ppe-video-aspect-ratio').val('16-9');

			// Update button text
			var $addBtn = this.popup.find('.om-ppe-video-url-popup-add');
			$addBtn.text($addBtn.data('text-default'));

			this.popup.show();
		},

		/**
		 * Edit existing video item.
		 *
		 * @param {jQuery} $item The video item to edit.
		 */
		editVideoItem: function($item) {
			var $input = $item.find('input[type="hidden"]');
			var value = $input.val();
			var loop = $input.attr('name').match(/\[(\d+)\]/)[1];

			try {
				var data = JSON.parse(value);

				this.currentLoop = loop;
				this.editingItem = $item;
				this.popup = $('.om-ppe-video-url-popup');

				// Fill form with existing data
				this.popup.find('#om-ppe-video-url').val(data.url || '');
				this.popup.find('#om-ppe-video-title').val(data.title || '');
				this.popup.find('#om-ppe-video-aspect-ratio').val(data.aspect_ratio || '16-9');

				// Update button text
				var $addBtn = this.popup.find('.om-ppe-video-url-popup-add');
				$addBtn.text($addBtn.data('text-update'));

				this.popup.show();
			} catch (e) {
				console.error('Failed to parse video data:', e);
			}
		},

		/**
		 * Close video popup.
		 */
		closeVideoPopup: function() {
			if (this.popup) {
				this.popup.hide();
				this.currentLoop = null;
				this.editingItem = null;
			}
		},

		/**
		 * Add video from popup.
		 */
		addVideoFromPopup: function() {
			var url = this.popup.find('#om-ppe-video-url').val().trim();
			var title = this.popup.find('#om-ppe-video-title').val().trim();
			var aspectRatio = this.popup.find('#om-ppe-video-aspect-ratio').val();

			if (!url) {
				alert( __( 'Please enter a video URL', 'ai-eshop-optimizer' ) );
				return;
			}

			// Validate URL (YouTube or Vimeo)
			if (!url.match(/(youtube|youtu\.be|vimeo)/)) {
				alert( __( 'Please enter a valid YouTube or Vimeo URL', 'ai-eshop-optimizer' ) );
				return;
			}

			var videoData = JSON.stringify({
				url: url,
				title: title,
				aspect_ratio: aspectRatio
			});

			var placeholder = typeof omPPEVariationsGallery !== 'undefined' ? omPPEVariationsGallery.placeholderVideoUrl : '';
			var editText = typeof omPPEVariationsGallery !== 'undefined' ? omPPEVariationsGallery.editText : 'Edit';

			if (this.editingItem) {
				// Update existing item
				this.editingItem.find('input[type="hidden"]').val(videoData);
			} else {
				// Create new item
				var $sortable = $('[name="botiga_variation_gallery[' + this.currentLoop + '][]"]')
					.first()
					.closest('.om-ppe-variation-gallery')
					.find('.om-ppe-variation-gallery-sortable');

				// If no existing items, find by loop index
				if (!$sortable.length) {
					$sortable = $('.om-ppe-add-video-url[data-loop="' + this.currentLoop + '"]')
						.closest('.om-ppe-variation-gallery')
						.find('.om-ppe-variation-gallery-sortable');
				}

				var $item = $('<li class="om-ppe-video-url-thumbnail">');
				$item.append('<figure data-edit-text="' + editText + '"><img src="' + placeholder + '" alt="" /></figure>');
				$item.append('<span class="om-ppe-remove-item dashicons dashicons-no"></span>');
				$item.append('<input type="hidden" name="botiga_variation_gallery[' + this.currentLoop + '][]" value=\'' + videoData + '\' />');

				$sortable.append($item);
			}

			// Trigger WooCommerce change detection
			var $variation = this.editingItem
				? this.editingItem.closest('.woocommerce_variation')
				: $sortable.closest('.woocommerce_variation');
			$variation.addClass('variation-needs-update');
			$('button.cancel-variation-changes, button.save-variation-changes').prop('disabled', false);
			$('#woocommerce-product-data').trigger('woocommerce_variations_input_changed');

			this.closeVideoPopup();
		}
	};

	// Initialize on document ready
	$(document).ready(function() {
		OMPPEVariationsGalleryAdmin.init();
	});

})(jQuery);
