/**
 * Sifency Addons Widget Duplication Handler
 * 
 * Handles widget duplication in Elementor editor via context menu
 */

(function($) {
	'use strict';

	var SifencyWidgetDuplication = {

		init: function() {
			// Add duplicate button to widget context menu
			this.addDuplicateButton();
			this.setupFavoritesToggle();
		},

		addDuplicateButton: function() {
			var self = this;

			// Hook into Elementor's context menu
			if (window.elementor && window.elementor.view) {
				// Add duplicate action when context menu is created
				jQuery(document).on('click', '.elementor-element', function(e) {
					if (e.which === 3) { // Right click
						self.showContextMenu(e);
					}
				});

				// Monitor for Elementor's built-in edit panel
				jQuery(document).on('click', '.elementor-element-edit', function() {
					self.addDuplicateAction();
				});
			}
		},

		showContextMenu: function(e) {
			var $element = jQuery(e.target).closest('.elementor-element');
			if (!$element.length) return;

			var elementId = $element.data('id');
			var elementType = $element.data('element_type');

			if (!elementId) return;

			// Create context menu
			var $menu = jQuery('<div class="sifency-context-menu">')
				.html(`
					<button class="sifency-context-btn sifency-duplicate-btn" data-element-id="${elementId}">
						<span class="dashicon">📋</span>
						${sifencyWidgetDuplication.l10n.duplicate || 'Duplicate'}
					</button>
				`);

			// Position and show
			jQuery('body').append($menu);
			$menu.css({
				position: 'fixed',
				top: (e.pageY - 10) + 'px',
				left: (e.pageX - 10) + 'px',
				zIndex: 99999
			}).show();

			// Hide on click outside
			jQuery(document).one('click', function() {
				$menu.remove();
			});

			e.preventDefault();
			return false;
		},

		addDuplicateAction: function() {
			var self = this;

			// Add to Elementor's element toolbar
			jQuery('.elementor-element-control').each(function() {
				var $control = jQuery(this);

				if (!$control.find('.sifency-duplicate-control').length) {
					var $duplicate = jQuery(`
						<button class="elementor-control-tool sifency-duplicate-control" 
							title="${sifencyWidgetDuplication.l10n.duplicate || 'Duplicate Widget'}"
							data-tooltip="${sifencyWidgetDuplication.l10n.duplicate || 'Duplicate Widget'}">
							<i class="eicon-clone"></i>
						</button>
					`);

					// Insert after copy button
					$control.append($duplicate);

					// Handle click
					$duplicate.on('click', function(e) {
						e.preventDefault();
						var $element = jQuery(this).closest('.elementor-element');
						var elementId = $element.data('id');

						if (elementId) {
							self.duplicateWidget(elementId);
						}
					});
				}
			});
		},

		duplicateWidget: function(elementId) {
			var $element = jQuery(`[data-id="${elementId}"]`);
			if (!$element.length) return;

			// Create duplicate by cloning
			var $clone = $element.clone(true);
			var newId = 'element-' + Math.random().toString(36).substr(2, 9);

			// Update ID
			$clone.data('id', newId);
			$clone.attr('data-id', newId);

			// Update nested IDs
			$clone.find('[data-id]').each(function() {
				var $nested = jQuery(this);
				var nestedId = 'element-' + Math.random().toString(36).substr(2, 9);
				$nested.data('id', nestedId);
				$nested.attr('data-id', nestedId);
			});

			// Insert after original
			$element.after($clone);

			// Add success notification
			this.showNotification('success', sifencyWidgetDuplication.l10n.duplicated || 'Widget duplicated successfully');

			// Trigger Elementor to recognize the new element
			if (window.elementor && window.elementor.trigger) {
				window.elementor.trigger('element:duplicate', {
					oldId: elementId,
					newId: newId
				});
			}
		},

		setupFavoritesToggle: function() {
			var self = this;

			jQuery(document).on('click', '.sifency-favorite-btn', function(e) {
				e.preventDefault();
				var $btn = jQuery(this);
				var widgetName = $btn.data('widget-name');

				if (!widgetName) return;

				self.toggleFavorite(widgetName, $btn);
			});
		},

		toggleFavorite: function(widgetName, $btn) {
			jQuery.ajax({
				url: sifencyWidgetDuplication.ajaxurl,
				type: 'POST',
				data: {
					action: 'sifency_widget_favorite',
					nonce: sifencyWidgetDuplication.nonce,
					widget_name: widgetName
				},
				success: function(response) {
					if (response.success) {
						var isFavorite = response.data.is_favorite;

						if (isFavorite) {
							$btn.addClass('is-favorite');
							this.showNotification('success', widgetName + ' added to favorites');
						} else {
							$btn.removeClass('is-favorite');
							this.showNotification('info', widgetName + ' removed from favorites');
						}
					} else {
						this.showNotification('error', response.data || 'Error toggling favorite');
					}
				}.bind(this),
				error: function() {
					this.showNotification('error', 'Error toggling favorite');
				}.bind(this)
			});
		},

		showNotification: function(type, message) {
			// Create notification element
			var $notification = jQuery(`
				<div class="sifency-notification sifency-notification-${type}">
					<span>${message}</span>
				</div>
			`);

			jQuery('body').append($notification);

			// Auto-remove after 3 seconds
			setTimeout(function() {
				$notification.fadeOut(function() {
					jQuery(this).remove();
				});
			}, 3000);
		}
	};

	// Initialize when document is ready
	jQuery(document).ready(function() {
		SifencyWidgetDuplication.init();
	});

	// Also initialize when Elementor editor is ready
	jQuery(window).on('elementor:init', function() {
		SifencyWidgetDuplication.init();
	});

})(jQuery);
