/**
 * Funnel Analytics JavaScript - Horizontal Steps with Vertical Bars
 *
 * Creates horizontal step visualization matching reference design
 *
 * @package opti-behavior
 * @version 2.0.0
 */

(function($) {
	'use strict';

	// i18n helper – pull localized strings from PHP with English fallbacks
	const _s = (window.optiBehaviorFunnels && window.optiBehaviorFunnels.strings) || {};
	function funnelMatchOptions(selected) {
		const opts = [
			{ v: 'any',        l: _s.anyPage       || 'Any Page' },
			{ v: 'exact',      l: _s.exactUrl       || 'Exact URL' },
			{ v: 'contains',   l: _s.urlContains    || 'URL Contains' },
			{ v: 'starts_with',l: _s.urlStartsWith  || 'URL Starts With' },
			{ v: 'ends_with',  l: _s.urlEndsWith    || 'URL Ends With' },
			{ v: 'regex',      l: _s.regex           || 'Regex' },
			{ v: 'pageview',   l: _s.anyPageView     || 'Any Page View' },
		];
		return opts.map(o => `<option value="${o.v}"${selected === o.v ? ' selected' : ''}>${o.l}</option>`).join('');
	}

	let currentPeriod = '7days';
	let currentFilter = 'all';
	let selectedCountriesByFunnel = {}; // Object mapping funnel ID to array of selected country codes
	let customStartDate = '';
	let customEndDate = '';

	/**
	 * Get selected countries for a specific funnel
	 */
	function getSelectedCountries(funnelId) {
		return selectedCountriesByFunnel[funnelId] || [];
	}

	/**
	 * Set selected countries for a specific funnel
	 */
	function setSelectedCountries(funnelId, countries) {
		selectedCountriesByFunnel[funnelId] = countries;
	}

	/**
	 * Initialize funnel analytics
	 */
	function initFunnelAnalytics() {
		// Setup event listeners
		setupEventListeners();

		// Initial data is loaded by loadFunnelsList()
		// which is called separately in document.ready
	}

	/**
	 * Setup event listeners
	 */
	function setupEventListeners() {
		// Period dropdown toggle (using delegation for dynamically loaded content)
		$(document).on('click', '.funnel-period-btn', function(e) {
			e.stopPropagation();
			const $dropdown = $(this).siblings('.period-dropdown');
			const $allDropdowns = $('.period-dropdown');

			// Hide all other dropdowns first
			$allDropdowns.not($dropdown).hide();
			// Then toggle this one
			$dropdown.toggle();
		});

		// Device dropdown toggle
		$(document).on('click', '.funnel-device-btn', function(e) {
			e.stopPropagation();
			const $dropdown = $(this).siblings('.device-dropdown');
			const $allDropdowns = $('.period-dropdown');

			// Hide all other dropdowns first
			$allDropdowns.not($dropdown).hide();
			// Then toggle this one
			$dropdown.toggle();
		});

		// Country dropdown toggle
		$(document).on('click', '.funnel-country-btn', function(e) {
			e.stopPropagation();
			const $dropdown = $(this).siblings('.country-dropdown');
			const $allDropdowns = $('.period-dropdown');

			// Hide all other dropdowns first
			$allDropdowns.not($dropdown).hide();
			// Then toggle this one
			$dropdown.toggle();
		});

		// Prevent country dropdown from closing when clicking inside (for search, checkboxes)
		$(document).on('click', '.country-dropdown', function(e) {
			e.stopPropagation();
		});

		// Country search filter
		$(document).on('input', '.country-search-input', function() {
			const searchTerm = $(this).val().toLowerCase();
			const $container = $(this).closest('.country-dropdown').find('.country-options-container');

			$container.find('.country-option-item').each(function() {
				const countryName = $(this).find('.country-name').text().toLowerCase();
				if (countryName.includes(searchTerm)) {
					$(this).show();
				} else {
					$(this).hide();
				}
			});
		});

		// Country checkbox change - store selection per funnel
		$(document).on('change', '.country-checkbox', function() {
			const countryCode = $(this).data('country');
			const funnelId = $(this).closest('.funnel-card').data('funnel-id');
			let countries = getSelectedCountries(funnelId);

			if ($(this).is(':checked')) {
				if (!countries.includes(countryCode)) {
					countries.push(countryCode);
				}
			} else {
				countries = countries.filter(c => c !== countryCode);
			}
			setSelectedCountries(funnelId, countries);
		});

		// Clear countries button - clear only for this funnel
		$(document).on('click', '.country-clear-btn', function() {
			const $dropdown = $(this).closest('.country-dropdown');
			const funnelId = $(this).closest('.funnel-card').data('funnel-id');
			$dropdown.find('.country-checkbox').prop('checked', false);
			setSelectedCountries(funnelId, []);
		});

		// Apply countries button - apply only for this funnel
		$(document).on('click', '.country-apply-btn', function() {
			const $dropdown = $(this).closest('.country-dropdown');
			const $funnelCard = $(this).closest('.funnel-card');
			const funnelId = $funnelCard.data('funnel-id');

			// Update label for THIS funnel only
			updateCountryLabelForFunnel(funnelId);

			// Close dropdown
			$dropdown.hide();

			// Reload only THIS funnel with new country filter
			loadFunnelAnalytics(funnelId);
		});

		// Close dropdown when clicking outside
		$(document).on('click', function(e) {
			if (!$(e.target).closest('.funnel-control-btn, .period-dropdown, .funnel-control-wrapper').length) {
				$('.period-dropdown').hide();
			}
		});

		// Period selection (using delegation for dynamically loaded content)
		$(document).on('click', '.period-option', function() {
			const period = $(this).data('period');
			const device = $(this).data('device');
			const country = $(this).data('country');

			// Handle time period selection
			if (period !== undefined) {
				// If custom range is selected, show date picker modal
				if (period === 'custom') {
					showCustomRangePicker($(this));
					return;
				}

				currentPeriod = period;

				// Update ALL period labels on the page
				$('.funnel-period-label').text($(this).text());

				// Close dropdown
				$('.period-dropdown').hide();

				// Reload analytics for all visible funnels
				reloadAllFunnelAnalytics();
			}
			// Handle device selection
			else if (device !== undefined) {
				currentFilter = device;

				// Update all device labels on the page
				$('.funnel-device-label').text($(this).text());

				// Hide all device dropdowns
				$('.device-dropdown').hide();

				// Reload all funnels
				reloadAllFunnelAnalytics();
			}
			// Country selection is now handled via checkboxes and Apply button
		});

		// Custom range modal close
		$(document).on('click', '#close-custom-range, #cancel-custom-range, .custom-range-overlay', function() {
			$('#custom-range-modal').remove();
		});

		// Apply custom range
		$(document).on('click', '#apply-custom-range', function() {
			const startDate = $('#custom-start-date').val();
			const endDate = $('#custom-end-date').val();

			if (!startDate || !endDate) {
				alert('Please select both start and end dates');
				return;
			}

			if (new Date(startDate) > new Date(endDate)) {
				alert('Start date must be before end date');
				return;
			}

			customStartDate = startDate;
			customEndDate = endDate;
			currentPeriod = 'custom';

			// Update ALL period labels
			$('.funnel-period-label').text(_s.customRange || 'Custom Range');

			// Close modal and dropdown
			$('#custom-range-modal').remove();
			$('.period-dropdown').hide();

			// Reload analytics for all visible funnels
			reloadAllFunnelAnalytics();
		});

		// Update URL pattern placeholder when match type changes
		$(document).on('change', '.step-match-type', function() {
			const matchType = $(this).val();
			const $urlPattern = $(this).closest('.step-fields').find('.step-url-pattern');

			const placeholders = {
				'any': 'No pattern needed - matches all URLs',
				'exact': 'Example: https://example.com/checkout',
				'contains': 'Example: /product (matches any URL containing /product)',
				'starts_with': 'Example: https://example.com (matches URLs starting with this)',
				'ends_with': 'Example: .pdf (matches URLs ending with .pdf)',
				'regex': 'Example: product/[0-9]+ (matches product/123, product/456)',
				'pageview': 'No pattern needed - matches all page views'
			};

			$urlPattern.attr('placeholder', placeholders[matchType] || 'Enter URL pattern');

			// Disable input for 'any' and 'pageview' since no pattern is needed
			if (matchType === 'any' || matchType === 'pageview') {
				$urlPattern.prop('disabled', true).val('');
			} else {
				$urlPattern.prop('disabled', false);
			}
		});

	}

	/**
	 * Show custom range picker modal
	 */
	function showCustomRangePicker($button) {
		// Remove existing modal if any
		$('#custom-range-modal').remove();

		// Get today's date for max attribute
		const today = new Date().toISOString().split('T')[0];

		// Create modal HTML
		const modalHtml = `
			<div id="custom-range-modal" class="funnel-builder-modal">
				<div class="custom-range-overlay funnel-builder-overlay"></div>
				<div class="funnel-builder-content" style="max-width: 500px;">
					<div class="funnel-builder-header">
						<h2>Select Custom Date Range</h2>
						<button class="funnel-builder-close" id="close-custom-range">
							<span class="dashicons dashicons-no-alt"></span>
						</button>
					</div>
					<div class="funnel-builder-body">
						<div class="form-field">
							<label for="custom-start-date">Start Date</label>
							<input type="date" id="custom-start-date" max="${today}" required />
						</div>
						<div class="form-field">
							<label for="custom-end-date">End Date</label>
							<input type="date" id="custom-end-date" max="${today}" required />
						</div>
					</div>
					<div class="funnel-builder-footer">
						<button type="button" class="btn-cancel" id="cancel-custom-range">Cancel</button>
						<button type="button" class="btn-save-funnel" id="apply-custom-range">Apply</button>
					</div>
				</div>
			</div>
		`;

		// Append to body and show
		$('body').append(modalHtml);
		$('#custom-range-modal').show();

		// Set default dates if custom dates exist
		if (customStartDate && customEndDate) {
			$('#custom-start-date').val(customStartDate);
			$('#custom-end-date').val(customEndDate);
		}

		// Close dropdown
		$('.period-dropdown').hide();
	}

	/**
	 * Reload analytics for all visible funnels (when period/filter changes)
	 */
	function reloadAllFunnelAnalytics() {
		// Find all funnel cards and reload their analytics and countries
		$('.funnel-card').each(function() {
			const funnelId = $(this).data('funnel-id');
			if (funnelId) {
				loadFunnelAnalytics(funnelId);
				// Also reload countries since available countries depend on date range
				loadAvailableCountries(funnelId);
			}
		});
	}

	/**
	 * Load available countries from the database for a specific funnel
	 * Only shows countries that have data for that funnel in the current date range
	 */
	function loadAvailableCountries(funnelId) {
		// Prepare request data
		const requestData = {
			action: 'optibehavior_get_funnel_countries',
			nonce: optiBehaviorFunnels.nonce,
			funnel_id: funnelId || 0,
			period: currentPeriod
		};

		// Add custom date range if selected
		if (currentPeriod === 'custom') {
			requestData.start_date = customStartDate;
			requestData.end_date = customEndDate;
		}

		$.ajax({
			url: optiBehaviorFunnels.ajaxUrl,
			type: 'POST',
			data: requestData,
			success: function(response) {
				if (response.success && response.data.countries) {
					const countries = response.data.countries;

					// Find the country dropdown for this specific funnel
					let $containers;
					if (funnelId) {
						$containers = $('.funnel-card[data-funnel-id="' + funnelId + '"] .country-options-container');
					} else {
						$containers = $('.country-options-container');
					}

					$containers.each(function() {
						const $container = $(this);
						$container.empty();

						if (countries.length === 0) {
							// Show message when no countries have data
							$container.html('<div class="no-countries-message">No country data available for this period</div>');
							return;
						}

						// Get selected countries for this specific funnel
						const selectedCountries = getSelectedCountries(funnelId);

						// Add each country as an option with checkbox and flag
						countries.forEach(function(country) {
							const countryCode = country.code.toLowerCase();
							const isChecked = selectedCountries.includes(country.code) || selectedCountries.includes(countryCode.toUpperCase());

							const $option = $('<label>')
								.addClass('country-option-item')
								.html(`
									<input type="checkbox" class="country-checkbox" data-country="${country.code}" ${isChecked ? 'checked' : ''}>
									<span class="fi fi-${countryCode}"></span>
									<span class="country-name">${country.name.toUpperCase()}</span>
								`);
							$container.append($option);
						});
					});
				}
			},
			error: function() {
				console.error('Failed to load countries');
			}
		});
	}

	/**
	 * Load countries for all visible funnels
	 */
	function loadAllFunnelCountries() {
		$('.funnel-card').each(function() {
			const funnelId = $(this).data('funnel-id');
			if (funnelId) {
				loadAvailableCountries(funnelId);
			}
		});
	}

	/**
	 * Update country label for a specific funnel
	 */
	function updateCountryLabelForFunnel(funnelId) {
		const selectedCountries = getSelectedCountries(funnelId);
		const $label = $('.funnel-card[data-funnel-id="' + funnelId + '"] .funnel-country-label');

		if (selectedCountries.length === 0) {
			$label.text(_s.allCountries || 'All Countries');
		} else if (selectedCountries.length === 1) {
			// Show the single country code
			const countryCode = selectedCountries[0];
			$label.text(countryCode.toUpperCase());
		} else {
			// Show count of selected countries
			$label.text(selectedCountries.length + ' Countries');
		}
	}

	/**
	 * Show error state
	 */
	function showErrorState() {
		$('#funnel-steps-header').html('<div class="funnel-loading"><span style="color: #dc2626;">Error loading data</span></div>');
	}

	/**
	 * Render funnel visualization
	 */
	function renderFunnelVisualization(data) {
		if (!data.funnel_steps || data.funnel_steps.length === 0) {
			$('#funnel-steps-header').html('<div class="funnel-loading"><span>No funnel data available</span></div>');
			return;
		}

		const steps = data.funnel_steps;
		const maxValue = steps[0].completed; // First step has highest value

		// Update top metrics badges
		updateMetricsBadges(data);

		// Render step headers (circles with numbers and names)
		renderStepHeaders(steps);

		// Render step bars
		renderStepBars(steps, maxValue);

		// Render step metrics
		renderStepMetrics(steps);
	}

	/**
	 * Update metrics badges
	 */
	function updateMetricsBadges(data) {
		$('#badge-1 .badge-value').text(formatNumberShort(data.total_entries));
		$('#badge-2 .badge-value').text(formatNumberShort(Math.round(data.total_entries * 0.75)));
		$('#badge-3 .badge-value').text(formatNumberShort(Math.round(data.total_entries * 0.65)));
		$('#badge-4 .badge-value').text(formatNumberShort(data.completed));
	}

	/**
	 * Render step headers
	 */
	function renderStepHeaders(steps) {
		const container = $('#funnel-steps-header');
		container.empty();

		steps.forEach(function(step, index) {
			const headerItem = `
				<div class="funnel-step-header-item">
					<div class="step-number-circle">${step.step_number}</div>
					<div class="step-name">${escapeHtml(step.step_name)}</div>
				</div>
			`;
			container.append(headerItem);
		});
	}

	/**
	 * Render step bars
	 */
	function renderStepBars(steps, maxValue) {
		const container = $('#funnel-steps-chart');
		container.empty();

		steps.forEach(function(step, index) {
			// Calculate bar height as percentage of max value
			const heightPercent = (step.completed / maxValue) * 100;

			// Determine color class based on completion rate
			let colorClass = '';
			if (step.completion_rate < 20) {
				colorClass = 'very-low-conversion';
			} else if (step.completion_rate < 50) {
				colorClass = 'low-conversion';
			}

			const barHtml = `
				<div class="step-bar-container">
					<div class="step-bar ${colorClass}" style="height: ${heightPercent}%;">
						<div class="step-percentage">${step.completion_rate}%</div>
					</div>
				</div>
			`;
			container.append(barHtml);
		});
	}

	/**
	 * Render step metrics
	 */
	function renderStepMetrics(steps) {
		const container = $('#funnel-steps-metrics');
		container.empty();

		steps.forEach(function(step, index) {
			const metricsHtml = `
				<div class="step-metrics-item">
					<div class="metric-row">
						<span class="metric-label">${_s.completed || 'Completed'}</span>
						<span class="metric-value completed">
							${formatNumber(step.completed)}
							<span class="metric-percentage positive">${step.completion_rate}%</span>
						</span>
					</div>
					<div class="metric-row">
						<span class="metric-label">${_s.abandoned || 'Abandoned'}</span>
						<span class="metric-value abandoned">
							${formatNumber(step.abandoned)}
							<span class="metric-percentage negative">${step.abandonment_rate}%</span>
						</span>
					</div>
				</div>
			`;
			container.append(metricsHtml);
		});
	}

	/**
	 * Format number with commas
	 */
	function formatNumber(num) {
		if (!num) return '0';
		return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
	}

	/**
	 * Format number to short format (K, M)
	 */
	function formatNumberShort(num) {
		if (!num) return '0';
		if (num >= 1000000) {
			return (num / 1000000).toFixed(1) + 'M';
		}
		if (num >= 1000) {
			return (num / 1000).toFixed(1) + 'K';
		}
		return num.toString();
	}

	/**
	 * Escape HTML
	 */
	function escapeHtml(text) {
		const map = {
			'&': '&amp;',
			'<': '&lt;',
			'>': '&gt;',
			'"': '&quot;',
			"'": '&#039;'
		};
		return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
	}

	/**
	 * Initialize funnel builder modal
	 */
	function initFunnelBuilder() {
		let stepCounter = 1;
		let editingFunnelId = null;

		// Open modal - handle both header button and empty state button
		$('.btn-build-funnel, .btn-build-funnel-primary').on('click', function() {
			editingFunnelId = null;
			resetFunnelBuilder();
			$('#save-funnel-builder').text(_s.saveFunnel || 'Save Funnel');
			$('#funnel-builder-modal').css('display', 'flex').addClass('show');
		});

		// Close modal
		$('#close-funnel-builder, #cancel-funnel-builder, .funnel-builder-overlay').on('click', function() {
			$('#funnel-builder-modal').removeClass('show');
			setTimeout(function() {
				$('#funnel-builder-modal').css('display', 'none');
				resetFunnelBuilder();
			}, 300);
		});

		// Add step
		$('#add-funnel-step').on('click', function() {
			stepCounter++;
			const stepHtml = `
				<div class="funnel-step-item" data-step="${stepCounter}">
					<div class="step-number">${stepCounter}</div>
					<div class="step-fields">
						<input type="text" class="step-name" placeholder="${_s.stepNamePlaceholder || 'Step name (e.g., Landing Page)'}" required />
						<select class="step-match-type">
							${funnelMatchOptions()}
						</select>
						<input type="text" class="step-url-pattern" placeholder="${_s.urlPatternPlaceholder || 'URL pattern (e.g., /cart)'}" />
					</div>
					<button type="button" class="remove-step">
						<span class="dashicons dashicons-trash"></span>
					</button>
				</div>
			`;
			$('#funnel-steps-container').append(stepHtml);
			updateRemoveButtons();
		});

		// Remove step (delegated event)
		$(document).on('click', '.remove-step', function() {
			$(this).closest('.funnel-step-item').remove();
			updateStepNumbers();
			updateRemoveButtons();
		});

		// Save funnel
		$('#save-funnel-builder').on('click', function() {
			saveFunnel();
		});

		function updateRemoveButtons() {
			const stepCount = $('.funnel-step-item').length;
			if (stepCount <= 1) {
				$('.remove-step').hide();
			} else {
				$('.remove-step').show();
			}
		}

		function updateStepNumbers() {
			$('.funnel-step-item').each(function(index) {
				$(this).attr('data-step', index + 1);
				$(this).find('.step-number').text(index + 1);
			});
		}

		function resetFunnelBuilder() {
			$('#funnel-name').val('');
			$('#funnel-description').val('');
			$('#funnel-steps-container').empty();

			// Add first step back
			stepCounter = 1;
			const firstStepHtml = `
				<div class="funnel-step-item" data-step="1">
					<div class="step-number">1</div>
					<div class="step-fields">
						<input type="text" class="step-name" placeholder="${_s.stepNamePlaceholder || 'Step name (e.g., Landing Page)'}" required />
						<select class="step-match-type">
							${funnelMatchOptions()}
						</select>
						<input type="text" class="step-url-pattern" placeholder="${_s.urlPatternPlaceholder || 'URL pattern (e.g., /cart)'}" />
					</div>
					<button type="button" class="remove-step" style="display: none;">
						<span class="dashicons dashicons-trash"></span>
					</button>
				</div>
			`;
			$('#funnel-steps-container').append(firstStepHtml);
		}

		function saveFunnel() {
			// Validate form
			const funnelName = $('#funnel-name').val().trim();
			if (!funnelName) {
				alert('Please enter a funnel name');
				return;
			}

			// Collect steps
			const steps = [];
			let valid = true;

			$('.funnel-step-item').each(function() {
				const stepName = $(this).find('.step-name').val().trim();
				const matchType = $(this).find('.step-match-type').val();
				const urlPattern = $(this).find('.step-url-pattern').val().trim();

				if (!stepName) {
					valid = false;
					alert('Please fill in all step names');
					return false;
				}

				steps.push({
					name: stepName,
					match_type: matchType,
					url_pattern: urlPattern || '*'
				});
			});

			if (!valid) {
				return;
			}

			const funnelDescription = $('#funnel-description').val().trim();

			// Disable save button
			$('#save-funnel-builder').prop('disabled', true).text('Saving...');

			// Prepare AJAX data
			const ajaxData = {
				action: 'optibehavior_save_funnel',
				nonce: optiBehaviorFunnels.nonce,
				name: funnelName,
				description: funnelDescription,
				steps: JSON.stringify(steps)
			};

			// Add funnel_id if editing
			if (editingFunnelId) {
				ajaxData.funnel_id = editingFunnelId;
			}

			// AJAX request to save funnel
			$.ajax({
				url: optiBehaviorFunnels.ajaxUrl,
				type: 'POST',
				data: ajaxData,
				success: function(response) {
					if (response.success) {
						// Close modal
						$('#funnel-builder-modal').removeClass('show');
						setTimeout(function() {
							$('#funnel-builder-modal').css('display', 'none');
							resetFunnelBuilder();
						}, 300);

						// Show pro-style success toast, then reload
						var msg = _s.funnelSavedSuccess || 'Funnel saved successfully!';
						var $toast = $('<div class="opti-toast opti-toast-success"><span class="opti-toast-icon">&#10003;</span> ' + $('<span>').text(msg).html() + '</div>');
						$toast.css({
							position: 'fixed', top: '60px', right: '30px', zIndex: 999999,
							background: 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
							color: '#fff', padding: '14px 28px', borderRadius: '10px',
							fontSize: '14px', fontWeight: 600,
							boxShadow: '0 8px 24px rgba(16,185,129,0.35)',
							display: 'flex', alignItems: 'center', gap: '10px',
							opacity: 0, transform: 'translateX(40px)',
							transition: 'all 0.4s cubic-bezier(.4,0,.2,1)'
						});
						$toast.find('.opti-toast-icon').css({
							background: 'rgba(255,255,255,0.25)', borderRadius: '50%',
							width: '26px', height: '26px', display: 'inline-flex',
							alignItems: 'center', justifyContent: 'center', fontSize: '14px'
						});
						$('body').append($toast);
						setTimeout(function(){ $toast.css({ opacity: 1, transform: 'translateX(0)' }); }, 50);
						setTimeout(function(){ $toast.css({ opacity: 0, transform: 'translateX(40px)' }); }, 2000);
						setTimeout(function(){ $toast.remove(); location.reload(); }, 2500);
					} else {
						alert('Error saving funnel: ' + (response.data.message || 'Unknown error'));
						$('#save-funnel-builder').prop('disabled', false).text(_s.saveFunnel || 'Save Funnel');
					}
				},
				error: function() {
					alert('Error saving funnel. Please try again.');
					$('#save-funnel-builder').prop('disabled', false).text(_s.saveFunnel || 'Save Funnel');
				}
			});
		}

		/**
		 * Load funnel data into the modal for editing
		 */
		window.loadFunnelForEdit = function(funnelId) {
			// Show loading state
			$('#funnel-builder-modal').css('display', 'flex').addClass('show');
			$('#funnel-name').val('Loading...').prop('disabled', true);
			$('#funnel-description').val('').prop('disabled', true);
			$('#save-funnel-builder').prop('disabled', true).text('Loading...');

			// Fetch funnel data
			$.ajax({
				url: optiBehaviorFunnels.ajaxUrl,
				type: 'POST',
				data: {
					action: 'optibehavior_get_funnel',
					nonce: optiBehaviorFunnels.nonce,
					funnel_id: funnelId
				},
				success: function(response) {
					if (response.success && response.data) {
						const funnel = response.data;

						// Set editing mode
						editingFunnelId = funnel.id;

						// Populate form
						$('#funnel-name').val(funnel.name).prop('disabled', false);
						$('#funnel-description').val(funnel.description || '').prop('disabled', false);

						// Clear existing steps
						$('#funnel-steps-container').empty();

						// Add steps from funnel
						stepCounter = 0;
						funnel.steps.forEach(function(step) {
							stepCounter++;
							const stepHtml = `
								<div class="funnel-step-item" data-step="${stepCounter}">
									<div class="step-number">${stepCounter}</div>
									<div class="step-fields">
										<input type="text" class="step-name" placeholder="${_s.stepNamePlaceholder || 'Step name (e.g., Landing Page)'}" value="${escapeHtml(step.name)}" required />
										<select class="step-match-type">
											${funnelMatchOptions(step.match_type)}
										</select>
										<input type="text" class="step-url-pattern" placeholder="${_s.urlPatternPlaceholder || 'URL pattern (e.g., /cart)'}" value="${escapeHtml(step.url_pattern || '')}" />
									</div>
									<button type="button" class="remove-step">
										<span class="dashicons dashicons-trash"></span>
									</button>
								</div>
							`;
							$('#funnel-steps-container').append(stepHtml);
						});

						updateRemoveButtons();

						// Update button text and enable
						$('#save-funnel-builder').prop('disabled', false).text(_s.updateFunnel || 'Update Funnel');
					} else {
						alert('Error loading funnel: ' + (response.data.message || 'Unknown error'));
						$('#funnel-builder-modal').removeClass('show');
						setTimeout(function() {
							$('#funnel-builder-modal').css('display', 'none');
						}, 300);
					}
				},
				error: function() {
					alert('Error loading funnel. Please try again.');
					$('#funnel-builder-modal').removeClass('show');
					setTimeout(function() {
						$('#funnel-builder-modal').css('display', 'none');
					}, 300);
				}
			});
		};

		/**
		 * Load funnel data for duplication
		 */
		window.loadFunnelForDuplicate = function(funnelId) {
			// Show loading state
			$('#funnel-builder-modal').css('display', 'flex').addClass('show');
			$('#funnel-name').val('Loading...').prop('disabled', true);
			$('#funnel-description').val('').prop('disabled', true);
			$('#save-funnel-builder').prop('disabled', true).text('Loading...');

			// Fetch funnel data
			$.ajax({
				url: optiBehaviorFunnels.ajaxUrl,
				type: 'POST',
				data: {
					action: 'optibehavior_get_funnel',
					nonce: optiBehaviorFunnels.nonce,
					funnel_id: funnelId
				},
				success: function(response) {
					if (response.success && response.data) {
						const funnel = response.data;

						// NOT in editing mode - creating new funnel
						editingFunnelId = null;

						// Populate form with "(Copy)" appended to name
						$('#funnel-name').val(funnel.name + ' (Copy)').prop('disabled', false);
						$('#funnel-description').val(funnel.description || '').prop('disabled', false);

						// Clear existing steps
						$('#funnel-steps-container').empty();

						// Add steps from funnel
						stepCounter = 0;
						funnel.steps.forEach(function(step) {
							stepCounter++;
							const stepHtml = `
								<div class="funnel-step-item" data-step="${stepCounter}">
									<div class="step-number">${stepCounter}</div>
									<div class="step-fields">
										<input type="text" class="step-name" placeholder="${_s.stepNamePlaceholder || 'Step name (e.g., Landing Page)'}" value="${escapeHtml(step.name)}" required />
										<select class="step-match-type">
											${funnelMatchOptions(step.match_type)}
										</select>
										<input type="text" class="step-url-pattern" placeholder="${_s.urlPatternPlaceholder || 'URL pattern (e.g., /cart)'}" value="${escapeHtml(step.url_pattern || '')}" />
									</div>
									<button type="button" class="remove-step">
										<span class="dashicons dashicons-trash"></span>
									</button>
								</div>
							`;
							$('#funnel-steps-container').append(stepHtml);
						});

						updateRemoveButtons();

						// Update button text and enable
						$('#save-funnel-builder').prop('disabled', false).text(_s.saveFunnel || 'Save Funnel');
					} else {
						alert('Error loading funnel: ' + (response.data.message || 'Unknown error'));
						$('#funnel-builder-modal').removeClass('show');
						setTimeout(function() {
							$('#funnel-builder-modal').css('display', 'none');
						}, 300);
					}
				},
				error: function() {
					alert('Error loading funnel. Please try again.');
					$('#funnel-builder-modal').removeClass('show');
					setTimeout(function() {
						$('#funnel-builder-modal').css('display', 'none');
					}, 300);
				}
			});
		};
	}

	/**
	 * Load and render all funnels
	 */
	function loadFunnelsList() {
		// Check if we have the funnels list container
		if ($('#funnels-list-container').length === 0) {
			return; // Empty state is showing
		}

		// Show loading state
		$('#funnels-list-container').html('<div class="funnel-loading"><span class="loading-spinner"></span><span>Loading funnels...</span></div>');

		// AJAX request to get all funnels
		$.ajax({
			url: optiBehaviorFunnels.ajaxUrl,
			type: 'POST',
			data: {
				action: 'optibehavior_get_funnels',
				nonce: optiBehaviorFunnels.nonce
			},
			success: function(response) {
				if (response.success && response.data && response.data.length > 0) {
					renderFunnelCards(response.data);
				} else {
					$('#funnels-list-container').html('<div class="funnel-loading"><span>No funnels found</span></div>');
				}
			},
			error: function() {
				$('#funnels-list-container').html('<div class="funnel-loading"><span style="color: #dc2626;">Error loading funnels</span></div>');
			}
		});
	}

	/**
	 * Render funnel cards from funnel data
	 */
	function renderFunnelCards(funnels) {
		const container = $('#funnels-list-container');
		container.empty();

		funnels.forEach(function(funnel) {
			const cardHtml = `
				<div class="funnel-card" data-funnel-id="${funnel.id}">
					<!-- Funnel Card Header -->
					<div class="funnel-card-header">
						<div class="funnel-title-section">
							<h2 class="funnel-title">${escapeHtml(funnel.name)}</h2>
							${funnel.description ? '<p class="funnel-description">' + escapeHtml(funnel.description) + '</p>' : ''}
						</div>
						<div class="funnel-controls">
							<!-- Time Period Filter -->
							<div class="funnel-control-wrapper">
								<button class="funnel-control-btn funnel-period-btn" data-funnel-id="${funnel.id}">
									<i data-lucide="calendar"></i>
									<span class="funnel-period-label">${_s.sevenDays || '7 Days'}</span>
									<span class="dashicons dashicons-arrow-down-alt2"></span>
								</button>
								<div class="period-dropdown" style="display: none;">
									<button class="period-option" data-period="7days">${_s.sevenDays || '7 Days'}</button>
									<button class="period-option" data-period="30days">${_s.thirtyDays || '30 Days'}</button>
									<button class="period-option" data-period="90days">${_s.ninetyDays || '90 Days'}</button>
									<button class="period-option" data-period="custom">${_s.customRange || 'Custom Range'}</button>
								</div>
							</div>

							<!-- Device Filter -->
							<div class="funnel-control-wrapper">
								<button class="funnel-control-btn funnel-device-btn" data-funnel-id="${funnel.id}">
									<i data-lucide="layout-grid"></i>
									<span class="funnel-device-label">${_s.allDevices || 'All Devices'}</span>
									<span class="dashicons dashicons-arrow-down-alt2"></span>
								</button>
								<div class="period-dropdown device-dropdown" style="display: none;">
									<button class="period-option" data-device="all">${_s.allDevices || 'All Devices'}</button>
									<button class="period-option" data-device="desktop">${_s.desktop || 'Desktop'}</button>
									<button class="period-option" data-device="mobile">${_s.mobile || 'Mobile'}</button>
									<button class="period-option" data-device="tablet">${_s.tablet || 'Tablet'}</button>
								</div>
							</div>

							<!-- Country Filter -->
							<div class="funnel-control-wrapper">
								<button class="funnel-control-btn funnel-country-btn" data-funnel-id="${funnel.id}">
									<i data-lucide="globe"></i>
									<span class="funnel-country-label">${_s.allCountries || 'All Countries'}</span>
									<span class="dashicons dashicons-arrow-down-alt2"></span>
								</button>
								<div class="period-dropdown country-dropdown" style="display: none;">
									<div class="country-search-wrapper">
										<input type="text" class="country-search-input" placeholder="${_s.searchCountries || 'Search countries...'}">
									</div>
									<div class="country-options-container"></div>
									<div class="country-actions">
										<button type="button" class="country-clear-btn">${_s.clear || 'Clear'}</button>
										<button type="button" class="country-apply-btn">${_s.apply || 'Apply'}</button>
									</div>
								</div>
							</div>

							<!-- Top Metrics Badges -->
							<div class="funnel-metrics-badges">
								<span class="metric-badge metric-badge-blue" data-badge="1" data-funnel-id="${funnel.id}">
									<span class="dashicons dashicons-chart-bar"></span>
									<span class="badge-value">--</span>
								</span>
								<span class="metric-badge metric-badge-green" data-badge="4" data-funnel-id="${funnel.id}">
									<span class="dashicons dashicons-yes-alt"></span>
									<span class="badge-value">--</span>
								</span>
							</div>

							<div class="funnel-more-container">
								<button class="funnel-control-btn funnel-more-btn" data-funnel-id="${funnel.id}">
									<span class="dashicons dashicons-ellipsis"></span>
								</button>
								<div class="funnel-more-dropdown" data-funnel-id="${funnel.id}">
									<button class="edit-funnel" data-funnel-id="${funnel.id}">
										<span class="dashicons dashicons-edit"></span>
										${_s.editFunnel || 'Edit Funnel'}
									</button>
									<button class="duplicate-funnel" data-funnel-id="${funnel.id}">
										<span class="dashicons dashicons-admin-page"></span>
										${_s.duplicate || 'Duplicate'}
									</button>
									<button class="reset-funnel-data" data-funnel-id="${funnel.id}">
										<span class="dashicons dashicons-update"></span>
										${_s.resetData || 'Reset Data'}
									</button>
									<button class="delete-funnel" data-funnel-id="${funnel.id}">
										<span class="dashicons dashicons-trash"></span>
										${_s.delete || 'Delete'}
									</button>
								</div>
							</div>
						</div>
					</div>

					<!-- Funnel Steps Visualization -->
					<div class="funnel-steps-wrapper">
						<div class="funnel-steps-label">${optiBehaviorFunnels.strings.steps || 'Steps'}</div>
						<div class="funnel-steps-container" data-funnel-id="${funnel.id}">
							<div class="funnel-loading">
								<span class="loading-spinner"></span>
								<span>${optiBehaviorFunnels.strings.loading || 'Loading funnel data...'}</span>
							</div>
						</div>
					</div>

					<!-- Pagination -->
					<div class="funnel-pagination">
						<button class="pagination-btn prev-page" data-funnel-id="${funnel.id}" disabled>
							<span class="dashicons dashicons-arrow-left-alt2"></span>
						</button>
						<button class="pagination-btn next-page" data-funnel-id="${funnel.id}">
							<span class="dashicons dashicons-arrow-right-alt2"></span>
						</button>
					</div>
				</div>
			`;
			container.append(cardHtml);

			// Load analytics data for this funnel
			loadFunnelAnalytics(funnel.id);
		});

		// Initialize Lucide icons
		if (typeof lucide !== 'undefined' && typeof lucide.createIcons === 'function') {
			lucide.createIcons();
		}

		// Load available countries for each funnel (filtered by funnel data)
		funnels.forEach(function(funnel) {
			loadAvailableCountries(funnel.id);
		});
	}

	/**
	 * Load analytics data for a specific funnel
	 */
	function loadFunnelAnalytics(funnelId) {
		// Get selected countries for THIS funnel
		const selectedCountries = getSelectedCountries(funnelId);

		// Prepare AJAX data
		const ajaxData = {
			action: 'optibehavior_funnel_data',
			nonce: optiBehaviorFunnels.nonce,
			funnel_id: funnelId,
			period: currentPeriod,
			filter: currentFilter,
			country: selectedCountries.length > 0 ? selectedCountries.join(',') : 'all'
		};

		// Add custom date range if selected
		if (currentPeriod === 'custom') {
			ajaxData.start_date = customStartDate;
			ajaxData.end_date = customEndDate;
		}

		$.ajax({
			url: optiBehaviorFunnels.ajaxUrl,
			type: 'POST',
			data: ajaxData,
			success: function(response) {
				if (response.success && response.data) {
					renderFunnelAnalytics(funnelId, response.data);
				} else {
					showFunnelError(funnelId);
				}
			},
			error: function() {
				showFunnelError(funnelId);
			}
		});
	}

	/**
	 * Render analytics for a specific funnel
	 */
	function renderFunnelAnalytics(funnelId, data) {
		if (!data.funnel_steps || data.funnel_steps.length === 0) {
			$('.funnel-steps-header[data-funnel-id="' + funnelId + '"]').html('<div class="funnel-loading"><span>No funnel data available</span></div>');
			return;
		}

		const steps = data.funnel_steps;
		const maxValue = steps[0].completed; // First step has highest value

		// Calculate real metrics from funnel steps
		const totalViews = steps.reduce(function(sum, step) { return sum + parseInt(step.completed) + parseInt(step.abandoned); }, 0);
		const firstStepTotal = parseInt(steps[0].completed) + parseInt(steps[0].abandoned);
		const uniqueUsers = data.total_entries || firstStepTotal;
		// Use the last step's completed count as the "funnel completed" metric (more intuitive)
		const lastStep = steps[steps.length - 1];
		const completedCount = lastStep ? parseInt(lastStep.completed) : (data.completed || 0);

		// Update top metrics badges with real data
		// Badge 1 (blue): Total entries / first step users
		$('.metric-badge[data-badge="1"][data-funnel-id="' + funnelId + '"] .badge-value').text(formatNumberShort(uniqueUsers));
		// Badge 4 (green): Users who completed the funnel (reached last step)
		$('.metric-badge[data-badge="4"][data-funnel-id="' + funnelId + '"] .badge-value').text(formatNumberShort(completedCount));

		// Render funnel steps - each step in its own bordered box with header inside
		const stepsContainer = $('.funnel-steps-container[data-funnel-id="' + funnelId + '"]');
		stepsContainer.empty();

		// Add "Steps" card with Y-axis labels as the first card
		const stepsCard = `
			<div class="funnel-step-card funnel-steps-axis-card">
				<div class="funnel-step-header">
					<div class="step-title">${_s.steps || 'Steps'}</div>
				</div>
				<div class="funnel-bar-container">
					<div class="funnel-y-axis-inline">
						<div class="funnel-y-axis-label">${formatNumberShort(maxValue)}</div>
						<div class="funnel-y-axis-label">${formatNumberShort(Math.round(maxValue * 0.67))}</div>
						<div class="funnel-y-axis-label">${formatNumberShort(Math.round(maxValue * 0.33))}</div>
						<div class="funnel-y-axis-label">0</div>
					</div>
				</div>
				<div class="funnel-step-metrics">
					<div class="funnel-y-axis-users">${_s.users || 'Users'}</div>
				</div>
			</div>
		`;
		stepsContainer.append(stepsCard);

		steps.forEach(function(step, index) {
			const heightPercent = Math.max((step.completed / maxValue) * 100, 5);
			const completionRate = step.completion_rate || 0;
			const abandonmentRate = step.abandonment_rate || 0;

			// Determine background and bar colors based on conversion
			let bgColor = '#fee2e2'; // Default light red
			let barColor = '#10b981'; // Default green

			if (completionRate >= 80) {
				bgColor = '#d1fae5'; // Light green
				barColor = '#10b981'; // Green
			} else if (completionRate >= 60) {
				bgColor = '#fef3c7'; // Light yellow
				barColor = '#10b981'; // Green
			} else if (completionRate >= 40) {
				bgColor = '#fed7aa'; // Light orange
				barColor = '#fb923c'; // Orange
			} else if (completionRate >= 20) {
				bgColor = '#fecaca'; // Light red
				barColor = '#f87171'; // Red
			} else {
				bgColor = '#fee2e2'; // Very light red
				barColor = '#ef4444'; // Strong red
			}

			const stepHtml = `
				<div class="funnel-step-card">
					<div class="funnel-step-header">
						<div class="step-circle">${step.step_number}</div>
						<div class="step-title" title="${escapeHtml(step.step_name)}">${escapeHtml(step.step_name)}</div>
					</div>
					<div class="funnel-bar-container">
						<div class="funnel-bar-background" style="background-color: ${bgColor};"></div>
						<div class="funnel-bar" style="height: ${heightPercent}%; background-color: ${barColor};">
							<div class="funnel-bar-percentage">${completionRate}%</div>
						</div>
					</div>
					<div class="funnel-step-metrics">
						<div class="funnel-metric-row">
							<div class="funnel-metric-section">
								<div class="funnel-metric-label">${_s.completed || 'Completed'}</div>
								<div class="funnel-metric-value">
									<span class="value-number">${formatNumber(step.completed)}</span>
									<span class="value-percent positive">${completionRate}%</span>
								</div>
							</div>
						</div>
						<div class="funnel-metric-row">
							<div class="funnel-metric-section">
								<div class="funnel-metric-label">${_s.abandoned || 'Abandoned'}</div>
								<div class="funnel-metric-value">
									<span class="value-number">${formatNumber(step.abandoned)}</span>
									<span class="value-percent negative">${abandonmentRate}%</span>
								</div>
							</div>
						</div>
					</div>
				</div>
			`;
			stepsContainer.append(stepHtml);
		});

		// Auto-hide pagination if all steps fit on screen
		updatePaginationVisibility(funnelId, steps.length);
	}

	/**
	 * Update pagination visibility based on number of steps
	 */
	function updatePaginationVisibility(funnelId, stepCount) {
		// Each step card is approximately 280px wide (240px + 40px gap)
		// Plus the Steps card is about 150px
		// Container width is typically 1400px max
		// We can fit approximately 4-5 step cards on screen at once

		// Pagination removed - users can scroll horizontally to see all steps
	}

	/**
	 * Show error for a specific funnel
	 */
	function showFunnelError(funnelId) {
		$('.funnel-steps-header[data-funnel-id="' + funnelId + '"]').html('<div class="funnel-loading"><span style="color: #dc2626;">Error loading data</span></div>');
	}

	/**
	 * Initialize funnel actions (edit, duplicate, delete)
	 */
	function initFunnelActions() {
		// Toggle dropdown menu
		$(document).on('click', '.funnel-more-btn', function(e) {
			e.stopPropagation();
			const dropdown = $(this).siblings('.funnel-more-dropdown');

			// Close all other dropdowns
			$('.funnel-more-dropdown').not(dropdown).removeClass('show');

			// Toggle this dropdown
			dropdown.toggleClass('show');
		});

		// Close dropdown when clicking outside
		$(document).on('click', function(e) {
			if (!$(e.target).closest('.funnel-more-container').length) {
				$('.funnel-more-dropdown').removeClass('show');
			}
		});

		// Prevent dropdown from closing when clicking inside it
		$(document).on('click', '.funnel-more-dropdown', function(e) {
			e.stopPropagation();
		});

		// Delete funnel
		$(document).on('click', '.delete-funnel', function(e) {
			e.preventDefault();
			e.stopPropagation();

			const funnelId = $(this).data('funnel-id');
			const funnelCard = $('.funnel-card[data-funnel-id="' + funnelId + '"]');
			const funnelName = funnelCard.find('.funnel-title').text();

			if (confirm('Are you sure you want to delete "' + funnelName + '"? This action cannot be undone.')) {
				deleteFunnel(funnelId);
			}

			// Close dropdown
			$('.funnel-more-dropdown').removeClass('show');
		});

		// Edit funnel
		$(document).on('click', '.edit-funnel', function(e) {
			e.preventDefault();
			e.stopPropagation();

			const funnelId = $(this).data('funnel-id');

			// Close dropdown
			$('.funnel-more-dropdown').removeClass('show');

			// Load funnel data and open modal for editing
			if (typeof window.loadFunnelForEdit === 'function') {
				window.loadFunnelForEdit(funnelId);
			}
		});

		// Duplicate funnel
		$(document).on('click', '.duplicate-funnel', function(e) {
			e.preventDefault();
			e.stopPropagation();

			const funnelId = $(this).data('funnel-id');

			// Close dropdown
			$('.funnel-more-dropdown').removeClass('show');

			// Load funnel data and open modal for duplication
			if (typeof window.loadFunnelForDuplicate === 'function') {
				window.loadFunnelForDuplicate(funnelId);
			}
		});

		// Reset funnel data
		$(document).on('click', '.reset-funnel-data', function(e) {
			e.preventDefault();
			e.stopPropagation();

			const funnelId = $(this).data('funnel-id');
			const funnelCard = $('.funnel-card[data-funnel-id="' + funnelId + '"]');
			const funnelName = funnelCard.find('.funnel-title').text();

			// Close dropdown
			$('.funnel-more-dropdown').removeClass('show');

			if (confirm('Are you sure you want to reset all data for "' + funnelName + '"?\n\nThis will delete all tracking data but keep the funnel configuration (steps and URLs).\n\nThis action cannot be undone.')) {
				resetFunnelData(funnelId);
			}
		});
	}

	/**
	 * Delete funnel via AJAX
	 */
	function deleteFunnel(funnelId) {
		const funnelCard = $('.funnel-card[data-funnel-id="' + funnelId + '"]');

		// Show loading state
		funnelCard.css('opacity', '0.5');
		funnelCard.find('.funnel-more-btn').prop('disabled', true);

		$.ajax({
			url: optiBehaviorFunnels.ajaxUrl,
			type: 'POST',
			data: {
				action: 'optibehavior_delete_funnel',
				nonce: optiBehaviorFunnels.nonce,
				funnel_id: funnelId
			},
			success: function(response) {
				if (response.success) {
					// Fade out and remove the card
					funnelCard.fadeOut(400, function() {
						$(this).remove();

						// Check if there are any funnels left
						if ($('.funnel-card').length === 0) {
							// Reload page to show empty state
							location.reload();
						}
					});
				} else {
					alert('Error deleting funnel: ' + (response.data.message || 'Unknown error'));
					funnelCard.css('opacity', '1');
					funnelCard.find('.funnel-more-btn').prop('disabled', false);
				}
			},
			error: function() {
				alert('Error deleting funnel. Please try again.');
				funnelCard.css('opacity', '1');
				funnelCard.find('.funnel-more-btn').prop('disabled', false);
			}
		});
	}

	/**
	 * Reset funnel data via AJAX (keeps funnel configuration, deletes tracking data)
	 */
	function resetFunnelData(funnelId) {
		const funnelCard = $('.funnel-card[data-funnel-id="' + funnelId + '"]');

		// Show loading state
		funnelCard.css('opacity', '0.5');
		funnelCard.find('.funnel-more-btn').prop('disabled', true);

		$.ajax({
			url: optiBehaviorFunnels.ajaxUrl,
			type: 'POST',
			data: {
				action: 'optibehavior_reset_funnel_data',
				nonce: optiBehaviorFunnels.nonce,
				funnel_id: funnelId
			},
			success: function(response) {
				if (response.success) {
					// Reload the funnel analytics to show fresh data (all zeros)
					loadFunnelAnalytics(funnelId);

					// Reset opacity
					funnelCard.css('opacity', '1');
					funnelCard.find('.funnel-more-btn').prop('disabled', false);

					// Show success message
					showFunnelToast(
						optiBehaviorFunnels.strings.resetDataSuccess ||
						'Funnel data has been reset successfully. The funnel configuration (steps and URLs) has been preserved.',
						'success'
					);
				} else {
					showFunnelToast(
						( optiBehaviorFunnels.strings.resetDataError || 'Error resetting funnel data' ) +
						': ' + ( response.data.message || optiBehaviorFunnels.strings.unknownError || 'Unknown error' ),
						'error'
					);
					funnelCard.css('opacity', '1');
					funnelCard.find('.funnel-more-btn').prop('disabled', false);
				}
			},
			error: function() {
				showFunnelToast(
					optiBehaviorFunnels.strings.resetDataNetworkError ||
					'Error resetting funnel data. Please try again.',
					'error'
				);
				funnelCard.css('opacity', '1');
				funnelCard.find('.funnel-more-btn').prop('disabled', false);
			}
		});
	}

	// =========================================================================
	// Toast Notifications
	// =========================================================================

	/**
	 * Show a brief, non-blocking toast notification.
	 *
	 * @param {string} message - Message to display.
	 * @param {string} type    - 'success' | 'error' | 'info'
	 */
	function showFunnelToast( message, type ) {
		type = type || 'success';
		var $toast = $( '<div class="opti-funnel-toast opti-funnel-toast--' + type + '"></div>' )
			.text( message ); // .text() auto-escapes HTML
		$( 'body' ).append( $toast );
		setTimeout( function() { $toast.addClass( 'show' ); }, 10 );
		setTimeout( function() {
			$toast.removeClass( 'show' );
			setTimeout( function() { $toast.remove(); }, 300 );
		}, 4000 );
	}

	// Initialize on document ready
	$(document).ready(function() {
		if ($('.opti-behavior-funnels-page').length > 0) {
			initFunnelAnalytics();
			initFunnelBuilder();
			loadFunnelsList();
			initFunnelActions();
		}
	});

})(jQuery);
