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

(function($) {
	'use strict';

	var SifencyWidgetDuplication = {

		init: function() {
			this.addDuplicateButton();
			this.setupFavoritesToggle();
		},

		addDuplicateButton: function() {
			var self = this;

			if (window.elementor && window.elementor.view) {
				jQuery(document).on('click', '.elementor-element', function(e) {
					if (e.which === 3) { // Right click
						self.showContextMenu(e);
					}
				});

				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;

			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>
				`);

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

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

			e.preventDefault();
			return false;
		},

		addDuplicateAction: function() {
			var self = this;

			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>
					`);

					$control.append($duplicate);

					$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;

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

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

			$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);
			});

			$element.after($clone);

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

			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) {
			var $notification = jQuery(`
				<div class="sifency-notification sifency-notification-${type}">
					<span>${message}</span>
				</div>
			`);

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

			setTimeout(function() {
				$notification.fadeOut(function() {
					jQuery(this).remove();
				});
			}, 3000);
		}
	};

	jQuery(document).ready(function() {
		SifencyWidgetDuplication.init();
	});

	jQuery(window).on('elementor:init', function() {
		SifencyWidgetDuplication.init();
	});

})(jQuery);
