<?php

namespace Unlockafe_addons\Classes;

use Unlockafe_addons\Classes\Widget_manager;

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly.

class Assets_loader {

	public $registered_widgets = array();
	public $Widget_manager;
	public function __construct( $registered_widgets ) {

		// assign widgets
		$this->registered_widgets = $registered_widgets;

		// creating instance
		$this->Widget_manager     = new Widget_manager( $this->registered_widgets );

		// hook execution
		$this->run_hooks();
	}

	/**
	 *
	 * Load css/js for public users
	 *
	 * @since  1.0.0
	 */
	public function load_public_scripts() {

		// load dependency
		$this->Widget_manager->load_plugin_dependency();

		// generate css
		$this->Widget_manager->build_elementor_assets();

		// adding preview assets
		$this->Widget_manager->add_elementor_assets();

		// Enqueue WordPress's default styles first
		// wp_enqueue_style('wp-style', get_stylesheet_uri());

		// adding global/general css
		wp_enqueue_style( UNLOCKAFE_init()::PREFIX . '-public', UNLOCKAFE_ASSETS . 'front-end/css/general.css', [ 'elementor-frontend' ], UNLOCKAFE_VERSION );

		// Mega Menu assets (required on frontend for interactions + animations)
		wp_enqueue_style(
			'unlockafe-mega-menu',
			UNLOCKAFE_ASSETS . 'front-end/css/mega-menu.css',
			['unlockafe-global'],
			UNLOCKAFE_VERSION
		);
		wp_enqueue_script(
			'unlockafe-mega-menu',
			UNLOCKAFE_ASSETS . 'front-end/js/mega-menu.js',
			['jquery'],
			UNLOCKAFE_VERSION,
			true
		);

		// Advance Mega Sidebar assets – load globally so it also works
		// when used inside header/footer templates or other Elementor locations
		// where widget-based asset detection might not run.
		wp_enqueue_style(
			'unlockafe-advance-mega-sidebar',
			UNLOCKAFE_ASSETS . 'front-end/css/advance-mega-sidebar.css',
			['unlockafe-global'],
			UNLOCKAFE_VERSION
		);
		wp_enqueue_script(
			'unlockafe-advance-mega-sidebar',
			UNLOCKAFE_ASSETS . 'front-end/js/advance-mega-sidebar.js',
			['jquery'],
			UNLOCKAFE_VERSION,
			true
		);

		// enqueue Font Awesome kit script
		wp_enqueue_script(
			'unlockafe-fontawesome-kit',
			'https://kit.fontawesome.com/1f253d1852.js',
			[],
			null,
			false
		);
		wp_script_add_data( 'unlockafe-fontawesome-kit', 'crossorigin', 'anonymous' );
	}


	/**
	 *
	 * Build Scripts for Admin
	 *
	 * @since  1.0.0
	 */
	public function unlockafe_load_admin_scripts( $admin_page ) {

		// menu pages 
		$unlockafe_menu = [ 
			'toplevel_page_unlock-addons',
			'unlock-addons_page_unlock-addons-elements',
			'unlock-addons_page_unlock-addons-integrations',
			'unlock-addons_page_unlock-addons-email-records',
			'unlock-addons_page_unlock-addons-support',
			'unlock-addons_page_unlock-addons-go-premium'
		];

		if ( ! in_array( $admin_page, $unlockafe_menu ) ) {
			return;
		}

		$asset_file = UNLOCKAFE_ADDONS_PATH . 'assets/build/index.asset.php';

		if ( ! file_exists( $asset_file ) ) {
			return;
		}

		$asset = include $asset_file;

		wp_enqueue_style( UNLOCKAFE_init()::PREFIX . '-admin', UNLOCKAFE_ASSETS . 'build/index.css', [], UNLOCKAFE_VERSION, 'all' );
		wp_enqueue_script( UNLOCKAFE_init()::PREFIX . '-admin', UNLOCKAFE_ASSETS . 'build/index.js', $asset['dependencies'], UNLOCKAFE_VERSION, true );

		wp_localize_script( UNLOCKAFE_init()::PREFIX . '-admin', 'unlockafe_data', [
			'_nonce' => wp_create_nonce('_unlockafe_nonce'),
			'email_records_nonce' => wp_create_nonce('unlockafe_email_records_nonce'),
			'ajaxurl' => admin_url('admin-ajax.php')
		]);
	}

	protected function run_hooks() {
		add_action( 'elementor/editor/after_save', [ $this->Widget_manager, 'unlockafe_elementor_after_save' ], 10, 2 );
		add_filter( 'elementor/files/file_name', [ $this->Widget_manager, 'singuler_file' ] );
		add_action( 'elementor/editor/after_enqueue_styles', [ $this->Widget_manager, 'unlockafe_editor_styles' ] );
		add_action( 'elementor/editor/after_enqueue_scripts', [ $this, 'unlockafe_editor_scripts' ] );

		// AJAX handlers for countdown reset
		add_action( 'wp_ajax_unlockafe_reset_countdown', [ $this, 'handle_reset_countdown' ] );
		add_action( 'wp_ajax_nopriv_unlockafe_reset_countdown', [ $this, 'handle_reset_countdown' ] );

		// Localize AI Chatbot script after it's enqueued
		add_action( 'wp_enqueue_scripts', [ $this, 'localize_ai_chatbot_script' ], 99 );
		
		// Suppress IE conditional comment deprecation warnings (WordPress 6.9.0+)
		// This warning comes from WordPress core when processing assets with IE conditional comments
		// Since IE conditional comments are deprecated and no longer needed, we suppress the warning
		if ( version_compare( get_bloginfo( 'version' ), '6.9.0', '>=' ) ) {
			// Use output buffering to catch and filter deprecation warnings
			add_action( 'init', [ $this, 'suppress_ie_conditional_deprecation' ], 1 );
		}

	}
	
	/**
	 * Suppress IE conditional comment deprecation warnings
	 * This suppresses the specific WordPress 6.9.0+ deprecation warning for IE conditional comments
	 */
	public function suppress_ie_conditional_deprecation() {
		// Suppress only the specific IE conditional comment deprecation warning
		// This is a WordPress core issue when processing assets, not from our code
		$previous_handler = set_error_handler( function( $errno, $errstr, $errfile, $errline ) use ( &$previous_handler ) {
			// Suppress only the specific IE conditional comment deprecation warning
			if ( $errno === E_USER_DEPRECATED && 
				 strpos( $errstr, 'WP_Dependencies->add_data()' ) !== false &&
				 strpos( $errstr, 'IE conditional comments' ) !== false ) {
				return true; // Suppress this specific warning
			}
			// Pass other errors to the previous handler or default handler
			if ( $previous_handler ) {
				return call_user_func( $previous_handler, $errno, $errstr, $errfile, $errline );
			}
			return false;
		}, E_USER_DEPRECATED );
	}

	/**
	 * Localize AI Chatbot script
	 */
	public function localize_ai_chatbot_script() {
		if (wp_script_is('unlockafe-ai-chatbot-scripts', 'registered')) {
			wp_localize_script('unlockafe-ai-chatbot-scripts', 'unlockafeChatbotData', [
				'ajaxUrl' => admin_url('admin-ajax.php'),
				'nonce' => wp_create_nonce('unlockafe_ai_chatbot_nonce'),
			]);
		}
	}

	/**
	 * Enqueue scripts for Elementor editor
	 *
	 * @since 1.0.0
	 */
	public function unlockafe_editor_scripts() {
		// Enqueue popup-anywhere.js for the editor to enable modal preview
		wp_enqueue_script(
			'unlockafe-popup-anywhere-editor',
			UNLOCKAFE_ASSETS . 'front-end/js/popup-anywhere.js',
			['jquery'],
			UNLOCKAFE_VERSION,
			true
		);

		wp_enqueue_style(
			'unlockafe-mega-menu',
			UNLOCKAFE_ASSETS . 'front-end/css/mega-menu.css',
			['unlockafe-global'],
			UNLOCKAFE_VERSION
		);

		wp_enqueue_script(
			'unlockafe-mega-menu',
			UNLOCKAFE_ASSETS . 'front-end/js/mega-menu.js',
			['jquery'],
			UNLOCKAFE_VERSION,
			true
		);

		wp_enqueue_script(
			'unlockafe-mega-menu-editor',
			UNLOCKAFE_ASSETS . 'editor/js/mega-menu-editor.js',
			['jquery'],
			UNLOCKAFE_VERSION,
			true
		);

		wp_enqueue_script(
			'unlockafe-advance-mega-menu-editor',
			UNLOCKAFE_ASSETS . 'editor/js/advance-mega-menu-editor.js',
			['jquery'],
			UNLOCKAFE_VERSION,
			true
		);
		wp_localize_script( 'unlockafe-advance-mega-menu-editor', 'unlockafe_amm_editor', [
			'ajaxurl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce( 'unlockafe_dummy_mega_menu' ),
		] );

		wp_enqueue_script(
			'unlockafe-advance-mega-sidebar-editor',
			UNLOCKAFE_ASSETS . 'editor/js/advance-mega-sidebar-editor.js',
			['jquery'],
			UNLOCKAFE_VERSION,
			true
		);

		// Ensure Font Awesome kit also loads inside Elementor editor
		wp_enqueue_script(
			'unlockafe-fontawesome-kit',
			'https://kit.fontawesome.com/1f253d1852.js',
			[],
			null,
			false
		);
		wp_script_add_data( 'unlockafe-fontawesome-kit', 'crossorigin', 'anonymous' );

		// Localize script with AJAX URL and nonce
		wp_localize_script('unlockafe-popup-anywhere-editor', 'unlockafe_ajax', [
			'ajaxurl' => admin_url('admin-ajax.php'),
			'nonce' => wp_create_nonce('unlockafe_reset_countdown')
		]);
		
		// Add inline script to replace widget icons with custom SVG for all unlockafe widgets
		$logo_url = UNLOCKAFE_ASSETS . 'images/unlockafe-editor.svg';
		wp_add_inline_script('unlockafe-popup-anywhere-editor', "
		(function() {
			var logoUrl = '{$logo_url}';
			
			function replaceWidgetIcons() {
				// Try multiple selectors to catch all widget variations (including filtered/search results)
				var selectors = [
					'.elementor-element-wrapper[data-widget*=\"unlockafe\"]',
					'.elementor-element-wrapper[data-widget^=\"unlockafe\"]',
					'.elementor-panel-element-wrapper[data-widget*=\"unlockafe\"]',
					'.elementor-panel-element-wrapper[data-widget^=\"unlockafe\"]',
					'[data-widget*=\"unlockafe\"]'
				];
				
				var allWidgets = [];
				selectors.forEach(function(selector) {
					try {
						var widgets = document.querySelectorAll(selector);
						widgets.forEach(function(widget) {
							if (allWidgets.indexOf(widget) === -1) {
								allWidgets.push(widget);
							}
						});
					} catch(e) {
						console.log('Selector error:', selector, e);
					}
				});
				
				allWidgets.forEach(function(wrapper) {
					// Try multiple ways to find the icon element
					var icon = null;
					var iconSelectors = [
						'i[class^=\"eicon-\"]',
						'i.eicon',
						'.eicon',
						'[class^=\"eicon-\"]',
						'.elementor-element-icon',
						'.elementor-element-icon-wrapper i',
						'.elementor-element-wrapper__icon i'
					];
					
					// Try each selector
					for (var i = 0; i < iconSelectors.length; i++) {
						icon = wrapper.querySelector(iconSelectors[i]);
						if (icon) break;
					}
					
					// If still not found, try finding by parent structure
					if (!icon) {
						var iconWrapper = wrapper.querySelector('.elementor-element-icon-wrapper, .elementor-element-wrapper__icon');
						if (iconWrapper) {
							icon = iconWrapper.querySelector('i, [class*=\"eicon\"], [class*=\"icon\"]') || iconWrapper.firstElementChild;
						}
					}
					
					// Last resort: find any i element in the wrapper
					if (!icon) {
						icon = wrapper.querySelector('i');
					}
					
					if (icon) {
						// Force re-process for search results - remove old attribute
						var isSearchResult = wrapper.closest('.elementor-panel-elements-search-results') || 
											wrapper.closest('.elementor-panel-search-results') ||
											document.querySelector('#elementor-panel-elements-search-input')?.value.length > 0;
						
						// For search results, always reprocess
						if (isSearchResult && icon.hasAttribute('data-unlockafe-icon-replaced')) {
							icon.removeAttribute('data-unlockafe-icon-replaced');
						}
						
						// Check if already processed (only skip if not in search)
						if (!isSearchResult && icon.hasAttribute('data-unlockafe-icon-replaced')) {
							return;
						}
						
						// Add custom class for CSS targeting
						icon.classList.add('unlockafe-custom-icon');
						wrapper.classList.add('unlockafe-widget-custom-icon');
						
						// Completely hide the original icon
						var originalDisplay = icon.style.display;
						icon.style.setProperty('font-size', '0', 'important');
						icon.style.setProperty('opacity', '0', 'important');
						icon.style.setProperty('line-height', '0', 'important');
						icon.style.setProperty('color', 'transparent', 'important');
						icon.style.setProperty('text-indent', '-9999px', 'important');
						
						// Set up background image replacement
						icon.style.setProperty('background-image', 'url(' + logoUrl + ')', 'important');
						icon.style.setProperty('background-size', 'contain', 'important');
						icon.style.setProperty('background-repeat', 'no-repeat', 'important');
						icon.style.setProperty('background-position', 'center center', 'important');
						icon.style.setProperty('width', '28px', 'important');
						icon.style.setProperty('height', '28px', 'important');
						icon.style.setProperty('min-width', '28px', 'important');
						icon.style.setProperty('min-height', '28px', 'important');
						icon.style.setProperty('display', 'inline-block', 'important');
						icon.style.setProperty('visibility', 'visible', 'important');
						icon.style.setProperty('opacity', '1', 'important');
						icon.style.setProperty('position', 'relative', 'important');
						
						// Hide ALL inner elements completely
						var innerIcons = icon.querySelectorAll('*');
						innerIcons.forEach(function(innerIcon) {
							innerIcon.style.setProperty('display', 'none', 'important');
							innerIcon.style.setProperty('visibility', 'hidden', 'important');
							innerIcon.style.setProperty('opacity', '0', 'important');
							innerIcon.style.setProperty('width', '0', 'important');
							innerIcon.style.setProperty('height', '0', 'important');
						});
						
						// Hide any pseudo-elements content
						var style = document.createElement('style');
						style.id = 'unlockafe-icon-replace-' + Date.now();
						style.textContent = '.unlockafe-custom-icon::before, .unlockafe-custom-icon::after { display: none !important; content: none !important; }';
						document.head.appendChild(style);
						
						// Mark as replaced
						icon.setAttribute('data-unlockafe-icon-replaced', 'true');
						icon.setAttribute('data-unlockafe-logo-url', logoUrl);
						
						// Also set parent wrapper styles if needed
						var iconParent = icon.parentElement;
						if (iconParent) {
							iconParent.style.setProperty('display', 'flex', 'important');
							iconParent.style.setProperty('align-items', 'center', 'important');
							iconParent.style.setProperty('justify-content', 'center', 'important');
							iconParent.style.setProperty('width', '28px', 'important');
							iconParent.style.setProperty('height', '28px', 'important');
						}
					}
				});
			}
			
			// Alias for backward compatibility
			function injectLogos() {
				replaceWidgetIcons();
			}
			
			function injectLogoIntoWrapper(wrapper) {
				if (wrapper.hasAttribute('data-unlockafe-addon-logo-injected')) return;
				var logo = document.createElement('span');
				logo.className = 'unlockafe-addon-logo';
				logo.setAttribute('aria-hidden', 'true');
				logo.style.cssText = 'display:block;width:35px;height:35px;min-width:35px;min-height:35px;position:absolute;top:8px;left:5px;background:url(' + logoUrl + ') no-repeat center center/contain;pointer-events:none;';
				var target = wrapper.querySelector('.elementor-element') || wrapper;
				if (target && !target.querySelector('.unlockafe-addon-logo')) {
					target.style.position = 'relative';
					target.style.paddingLeft = '45px';
					target.insertBefore(logo, target.firstChild);
					wrapper.setAttribute('data-unlockafe-addon-logo-injected', 'true');
				}
			}
			
			// Fallback: inject addon logo element in search results when CSS ::before is not enough
			function injectAddonLogoInSearchResults() {
				console.log('[Unlock Addons] injectAddonLogoInSearchResults called');
				var injectedCount = 0;
				var panel = document.querySelector('#elementor-panel-elements') || document.querySelector('#elementor-panel');
				
				// Panel-wide injection FIRST (container-agnostic approach)
				if (panel) {
					var allWrappers = panel.querySelectorAll('.elementor-element-wrapper[data-widget*=\"unlockafe\"], [data-widget*=\"unlockafe\"]');
					console.log('[Unlock Addons] Found', allWrappers.length, 'unlockafe widgets in panel');
					allWrappers.forEach(function(wrapper) {
						// Skip widgets that are inside category view
						if (wrapper.closest('#elementor-panel-category-unlockafe-addons')) return;
						var hadLogo = wrapper.hasAttribute('data-unlockafe-addon-logo-injected');
						injectLogoIntoWrapper(wrapper);
						if (!hadLogo && wrapper.hasAttribute('data-unlockafe-addon-logo-injected')) {
							injectedCount++;
						}
					});
					console.log('[Unlock Addons] Injected logo into', injectedCount, 'widgets (panel-wide)');
				}
				
				// Optional: also check specific search containers (if they exist)
				var searchContainers = [
					'.elementor-panel-elements-search-results',
					'.elementor-panel-search-results'
				];
				var containerFound = false;
				searchContainers.forEach(function(containerSel) {
					var container = document.querySelector(containerSel);
					if (container) {
						containerFound = true;
						var wrappers = container.querySelectorAll('.elementor-element-wrapper[data-widget*=\"unlockafe\"], [data-widget*=\"unlockafe\"]');
						wrappers.forEach(function(wrapper) {
							var hadLogo = wrapper.hasAttribute('data-unlockafe-addon-logo-injected');
							injectLogoIntoWrapper(wrapper);
							if (!hadLogo && wrapper.hasAttribute('data-unlockafe-addon-logo-injected')) {
								injectedCount++;
							}
						});
					}
				});
				if (containerFound) {
					console.log('[Unlock Addons] Also checked specific search containers');
				}
			}
			
			// Enhanced search handler with aggressive replacement
			function handleSearch() {
				// Clear all previous replacement markers to force re-processing
				var allIcons = document.querySelectorAll('.unlockafe-custom-icon[data-unlockafe-icon-replaced]');
				allIcons.forEach(function(icon) {
					icon.removeAttribute('data-unlockafe-icon-replaced');
				});
				// Clear addon logo injected marker in search results and panel-wide so it can re-run
				var searchRoots = document.querySelectorAll('.elementor-panel-elements-search-results, .elementor-panel-search-results');
				searchRoots.forEach(function(root) {
					root.querySelectorAll('[data-unlockafe-addon-logo-injected]').forEach(function(el) {
						el.removeAttribute('data-unlockafe-addon-logo-injected');
					});
					root.querySelectorAll('.unlockafe-addon-logo').forEach(function(el) {
						if (el.parentNode) el.parentNode.removeChild(el);
					});
				});
				var panel = document.querySelector('#elementor-panel-elements') || document.querySelector('#elementor-panel');
				if (panel) {
					panel.querySelectorAll('[data-widget*=\"unlockafe\"]').forEach(function(wrapper) {
						if (wrapper.closest('#elementor-panel-category-unlockafe-addons')) return;
						wrapper.removeAttribute('data-unlockafe-addon-logo-injected');
						var logo = wrapper.querySelector('.unlockafe-addon-logo');
						if (logo && logo.parentNode) logo.parentNode.removeChild(logo);
					});
				}
				
				// Immediate replacement
				replaceWidgetIcons();
				injectAddonLogoInSearchResults();
				// Multiple delayed replacements to catch all variations (including 200-800ms for slow render)
				setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 10);
				setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 50);
				setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 100);
				setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 150);
				setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 250);
				setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 300);
				setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 400);
				setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 500);
				setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 600);
				setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 800);
				setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 1000);
			}
			
			// Run immediately
			replaceWidgetIcons();
			injectAddonLogoInSearchResults();
			
			// Run on DOM ready
			if (document.readyState === 'loading') {
				document.addEventListener('DOMContentLoaded', function() {
					replaceWidgetIcons();
					injectAddonLogoInSearchResults();
					setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 200);
					setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 500);
				});
			} else {
				setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 100);
				setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 300);
			}
			
			// Enhanced MutationObserver to watch for all DOM changes including attribute changes
			if (typeof MutationObserver !== 'undefined') {
				var observer = new MutationObserver(function(mutations) {
					var shouldCheck = false;
					mutations.forEach(function(mutation) {
						// Check for added nodes
						if (mutation.addedNodes.length > 0) {
							mutation.addedNodes.forEach(function(node) {
								if (node.nodeType === 1) {
									if (node.classList && (
										node.classList.contains('elementor-element-wrapper') || 
										node.classList.contains('elementor-panel-element-wrapper') ||
										node.querySelector('.elementor-element-wrapper') ||
										node.querySelector('[data-widget*=\"unlockafe\"]')
									)) {
										shouldCheck = true;
									}
								}
							});
						}
						// Check for attribute changes (like display changes during search)
						if (mutation.type === 'attributes' && (
							mutation.attributeName === 'style' || 
							mutation.attributeName === 'class' ||
							mutation.attributeName === 'data-widget'
						)) {
							if (mutation.target && (
								mutation.target.classList.contains('elementor-element-wrapper') ||
								mutation.target.hasAttribute('data-widget')
							)) {
								shouldCheck = true;
							}
						}
					});
					if (shouldCheck) {
						setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 50);
						setTimeout(function() { replaceWidgetIcons(); injectAddonLogoInSearchResults(); }, 200);
					}
				});
				
				// Observe multiple panel elements
				var panelSelectors = [
					'#elementor-panel-elements',
					'.elementor-panel-elements',
					'.elementor-panel-elements-wrapper',
					'.elementor-panel',
					'#elementor-panel'
				];
				
				panelSelectors.forEach(function(selector) {
					var panel = document.querySelector(selector);
					if (panel) {
						observer.observe(panel, { 
							childList: true, 
							subtree: true,
							attributes: true,
							attributeFilter: ['style', 'class', 'data-widget']
						});
					}
				});
			}
			
			// More frequent periodic check (especially important for search)
			setInterval(function() {
				// Check if search is active
				var searchInput = document.querySelector('#elementor-panel-elements-search-input, .elementor-panel-elements-search-input');
				if (searchInput && searchInput.value && searchInput.value.length > 0) {
					replaceWidgetIcons();
					injectAddonLogoInSearchResults();
				}
			}, 200);
			
			// Also run general replacement periodically
			setInterval(replaceWidgetIcons, 500);
			
			// Enhanced search event listeners - multiple approaches
			if (typeof jQuery !== 'undefined') {
				// Remove old handlers first
				jQuery(document).off('input.unlockafe keyup.unlockafe paste.unlockafe change.unlockafe focus.unlockafe click.unlockafe');
				
				// Input events (typing in search) - use namespace
				jQuery(document).on('input.unlockafe keyup.unlockafe paste.unlockafe change.unlockafe', '#elementor-panel-elements-search-input, .elementor-panel-elements-search-input, input[placeholder*=\"Search\"], input[placeholder*=\"search\"]', function() {
					handleSearch();
				});
				
				// Click on search input
				jQuery(document).on('focus.unlockafe click.unlockafe', '#elementor-panel-elements-search-input, .elementor-panel-elements-search-input', function() {
					setTimeout(handleSearch, 100);
				});
				
				// Clear search
				jQuery(document).on('click.unlockafe', '.elementor-panel-search-clear, .elementor-panel-elements-search-input-clear, .elementor-panel-search-reset', function() {
					setTimeout(function() {
						replaceWidgetIcons();
						setTimeout(replaceWidgetIcons, 200);
					}, 100);
				});
			}
			
			// Native event listeners as backup with multiple event types
			var searchInputSelectors = [
				'#elementor-panel-elements-search-input',
				'.elementor-panel-elements-search-input',
				'input[placeholder*=\"Search\"]',
				'input[placeholder*=\"search\"]'
			];
			
			['input', 'keyup', 'keydown', 'paste', 'change'].forEach(function(eventType) {
				document.addEventListener(eventType, function(e) {
					if (e.target) {
						var isSearchInput = searchInputSelectors.some(function(selector) {
							return e.target.matches && e.target.matches(selector);
						}) || (e.target.placeholder && e.target.placeholder.toLowerCase().indexOf('search') !== -1);
						
						if (isSearchInput) {
							handleSearch();
						}
					}
				}, true);
			});
			
			// Elementor-specific events
			if (typeof elementor !== 'undefined') {
				elementor.hooks.addAction('panel/open_editor/widget/unlockafe', replaceWidgetIcons);
				elementor.on('preview:loaded', replaceWidgetIcons);
				
				// Listen for panel refresh
				if (elementor.hooks.addAction) {
					elementor.hooks.addAction('panel/elements/search', handleSearch);
				}
			}
		})();
		");

		// Add admin script for countdown reset functionality
		wp_add_inline_script('unlockafe-popup-anywhere-editor', '
			jQuery(document).ready(function($) {
				// Use event delegation to handle dynamically added buttons
				$(document).off("click.unlockafe").on("click.unlockafe", ".unlockafe-reset-btn", function(e) {
					e.preventDefault();
					
					var button = $(this);
					var template_prefix = button.data("template");
					var widget_id = button.data("widget-id");
					
					// If widget_id is empty or {{ID}}, try to find it from the DOM
					if (!widget_id || widget_id === "{{ID}}" || widget_id === "") {
						// Try multiple methods to find the widget ID
						var attempts = [
							function() { return button.closest("[data-id]").data("id"); },
							function() { return button.closest(".elementor-widget").data("id"); },
							function() { return button.closest("[data-element_type]").data("id"); },
							function() { return button.closest(".elementor-element").data("id"); },
							function() { return button.parents("[data-id]").first().data("id"); },
							function() { return button.parents(".elementor-widget").first().data("id"); },
							function() { 
								// Look for any parent with an ID that looks like a widget ID
								var parents = button.parents();
								for (var i = 0; i < parents.length; i++) {
									var el = $(parents[i]);
									var id = el.data("id") || el.attr("data-id");
									if (id && typeof id === "string" && id.length > 5) {
										return id;
									}
								}
								return null;
							}
						];
						
						for (var i = 0; i < attempts.length; i++) {
							try {
								var id = attempts[i]();
								if (id && id !== undefined && id !== "") {
									widget_id = id;
									console.log("Found widget ID using method " + (i + 1) + ":", id);
									break;
								}
							} catch(e) {
								console.log("Method " + (i + 1) + " failed:", e);
							}
						}
					}
					
					// Debug DOM structure
					console.log("DOM Structure Debug:");
					console.log("Button:", button[0]);
					console.log("Button parents with data-id:", button.parents("[data-id]").get());
					console.log("Button parents with class elementor-widget:", button.parents(".elementor-widget").get());
					console.log("Button parents with class elementor-element:", button.parents(".elementor-element").get());
					
					// Log all parent elements with their data attributes
					var allParents = button.parents();
					console.log("All parent elements:", allParents.get());
					allParents.each(function(index, element) {
						var $el = $(element);
						var dataAttrs = {};
						$.each(element.attributes, function() {
							if (this.name.indexOf("data-") === 0) {
								dataAttrs[this.name] = this.value;
							}
						});
						if (Object.keys(dataAttrs).length > 0) {
							console.log("Parent " + index + " (" + element.tagName + "." + element.className + "):", dataAttrs);
						}
					});

					console.log("Reset button clicked:", {
						template_prefix: template_prefix,
						widget_id: widget_id,
						button: button[0]
					});
					
					if (!template_prefix || !widget_id) {
						alert("❌ Error: Missing template or widget ID data");
						console.error("Missing data:", {template_prefix: template_prefix, widget_id: widget_id});
						return;
					}
					
					if (!confirm("Are you sure you want to reset the countdown timer? This will restart the countdown with current settings for ALL visitors.")) {
						return;
					}
					
					// Show loading state
					var originalText = button.html();
					button.html("🔄 Resetting...").prop("disabled", true);
					
					$.ajax({
						url: unlockafe_ajax.ajaxurl || ajaxurl || "/wp-admin/admin-ajax.php",
						type: "POST",
						dataType: "json",
						data: {
							action: "unlockafe_reset_countdown",
							template_prefix: template_prefix,
							widget_id: widget_id,
							nonce: unlockafe_ajax.nonce
						},
						success: function(response) {
							console.log("Reset response:", response);
							
							if (response && response.success) {
								alert("✅ " + (response.data || "Countdown timer has been reset successfully!"));
								// Reload Elementor preview to show new countdown
								if (window.elementor && window.elementor.reloadPreview) {
									window.elementor.reloadPreview();
								} else {
									// Fallback: reload the page
									window.location.reload();
								}
							} else {
								alert("❌ Error: " + (response.data || "Failed to reset countdown"));
							}
						},
						error: function(xhr, status, error) {
							console.error("AJAX Error:", xhr.responseText);
							console.error("Status:", status);
							console.error("Error:", error);
							
							var errorMsg = "Network error. Please try again.";
							if (xhr.responseText) {
								try {
									var errorResponse = JSON.parse(xhr.responseText);
									errorMsg = errorResponse.data || errorResponse.message || errorMsg;
								} catch(e) {
									errorMsg = "Server error: " + xhr.responseText.substring(0, 100);
								}
							}
							alert("❌ " + errorMsg);
						},
						complete: function() {
							// Restore button state
							button.html(originalText).prop("disabled", false);
						}
					});
				});
			});
		');
	}

	/**
	 * Handle AJAX request to reset countdown timer
	 *
	 * @since 1.0.0
	 */
	public function handle_reset_countdown() {
		// Set proper content type for JSON response
		header('Content-Type: application/json');

		try {
			// Verify nonce
			if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'unlockafe_reset_countdown')) {
				wp_send_json_error('Invalid security token');
				return;
			}

			// Check user permissions
			if (!current_user_can('edit_posts')) {
				wp_send_json_error('Insufficient permissions');
				return;
			}

			$template_prefix = isset($_POST['template_prefix']) ? sanitize_text_field($_POST['template_prefix']) : '';
			$widget_id = isset($_POST['widget_id']) ? sanitize_text_field($_POST['widget_id']) : '';

			if (empty($template_prefix) || empty($widget_id)) {
				wp_send_json_error('Missing required parameters: template_prefix or widget_id');
				return;
			}

			// Delete the countdown option to reset it
			$option_key = 'unlockafe_countdown_' . $widget_id . '_' . $template_prefix;
			
			// First check if option exists
			$option_exists = get_option($option_key, false);
			
			if ($option_exists !== false) {
				// Option exists, try to delete it
				$deleted = delete_option($option_key);
				if ($deleted) {
					wp_send_json_success('Countdown timer reset successfully! New countdown will start with current settings.');
				} else {
					wp_send_json_error('Failed to delete countdown option from database');
				}
			} else {
				// Option doesn't exist, consider it already reset
				wp_send_json_success('Countdown timer was already reset or not yet created. New countdown will start with current settings.');
			}

		} catch (Exception $e) {
			wp_send_json_error('Server error: ' . $e->getMessage());
		}
	}

}