/**
 * Leadite admin logic.
 */
(function () {
	'use strict';

	document.addEventListener('DOMContentLoaded', function () {
		// Bulk delete confirmation (uses localized string from wp_localize_script)
		document.querySelectorAll('form').forEach(function (form) {
			form.addEventListener('submit', function (e) {
				var selects = form.querySelectorAll('select[name="action"], select[name="action2"]');
				var destructive = false;
				selects.forEach(function (s) {
					if (s.value === 'delete') {
						destructive = true;
					}
				});
				if (destructive && !window.confirm(leaditeAdmin.confirmDelete)) {
					e.preventDefault();
				}
			});
		});

		// Danger Zone "Delete All" confirm (also localized)
		var dangerForm = document.querySelector('.leadite-danger-zone__form');
		if (dangerForm) {
			dangerForm.addEventListener('submit', function (e) {
				if (!window.confirm(leaditeAdmin.confirmDelete)) {
					e.preventDefault();
				}
			});
		}

		// Show / hide secret fields (Telegram token, Webhook URL)
		document.body.addEventListener('click', function (e) {
			var btn = e.target.closest('.leadite-secret-reveal');
			if (!btn) return;
			var targetId = btn.getAttribute('data-target');
			var input = document.getElementById(targetId);
			if (!input) return;
			var isHidden = input.type === 'password' || input.getAttribute('data-hidden') === '1';
			if (isHidden) {
				input.type = 'text';
				input.setAttribute('data-hidden', '0');
				btn.setAttribute('aria-pressed', 'true');
				btn.classList.add('leadite-secret-reveal--visible');
			} else {
				input.type = 'password';
				input.setAttribute('data-hidden', '1');
				btn.setAttribute('aria-pressed', 'false');
				btn.classList.remove('leadite-secret-reveal--visible');
			}
		});

		// SVG Line Chart Tooltips
		var chartWrapper = document.querySelector('.leadite-chart-wrapper');
		var tooltip = document.querySelector('.leadite-chart-tooltip');

		if (chartWrapper && tooltip) {
			var triggers = chartWrapper.querySelectorAll('.leadite-chart-trigger');

			triggers.forEach(function (trigger) {
				trigger.addEventListener('mouseenter', function () {
					var date = trigger.getAttribute('data-date');
					var count = parseInt(trigger.getAttribute('data-count'), 10);
					var index = parseInt(trigger.getAttribute('data-index'), 10);
					var cx = parseFloat(trigger.getAttribute('data-x'));
					var cy = parseFloat(trigger.getAttribute('data-y'));

					var targetDot = document.getElementById('leadite-dot-' + index);
					if (targetDot) {
						targetDot.classList.add('is-active');
					}

					tooltip.innerHTML = date + '<strong>' + count + ' ' + (count === 1 ? 'lead' : 'leads') + '</strong>';
					tooltip.style.opacity = '1';

					var svg = chartWrapper.querySelector('.leadite-svg-chart');
					var svgRect = svg.getBoundingClientRect();
					var wrapperRect = chartWrapper.getBoundingClientRect();

					var scaleX = svgRect.width / 800;
					var scaleY = svgRect.height / 250;

					var px = (cx * scaleX) + (svgRect.left - wrapperRect.left);
					var py = (cy * scaleY) + (svgRect.top - wrapperRect.top);

					tooltip.style.left = px + 'px';
					tooltip.style.top = (py - 10) + 'px';
					tooltip.style.transform = 'translate(-50%, -100%)';
				});

				trigger.addEventListener('mouseleave', function () {
					tooltip.style.opacity = '0';
					var index = trigger.getAttribute('data-index');
					var targetDot = document.getElementById('leadite-dot-' + index);
					if (targetDot) {
						targetDot.classList.remove('is-active');
					}
				});
			});
		}

		// Donut Chart Segment highlights
		var donutWrapper = document.querySelector('.leadite-donut-wrapper');
		if (donutWrapper) {
			var segments = donutWrapper.querySelectorAll('.leadite-donut-segment');
			var legendItems = donutWrapper.querySelectorAll('.leadite-legend-item');

			segments.forEach(function (segment) {
				segment.addEventListener('mouseenter', function () {
					var index = segment.getAttribute('data-index');

					segments.forEach(function (seg) {
						if (seg.getAttribute('data-index') !== index) {
							seg.classList.add('is-dimmed');
						}
					});

					var targetLegend = donutWrapper.querySelector('.leadite-legend-item[data-index="' + index + '"]');
					if (targetLegend) {
						targetLegend.classList.add('is-active');
					}
				});

				segment.addEventListener('mouseleave', function () {
					segments.forEach(function (seg) {
						seg.classList.remove('is-dimmed');
					});
					legendItems.forEach(function (item) {
						item.classList.remove('is-active');
					});
				});
			});

			legendItems.forEach(function (item) {
				item.addEventListener('mouseenter', function () {
					var index = item.getAttribute('data-index');

					segments.forEach(function (seg) {
						if (seg.getAttribute('data-index') !== index) {
							seg.classList.add('is-dimmed');
						}
					});

					item.classList.add('is-active');
				});

				item.addEventListener('mouseleave', function () {
					segments.forEach(function (seg) {
						seg.classList.remove('is-dimmed');
					});
					legendItems.forEach(function (item) {
						item.classList.remove('is-active');
					});
				});
			});
		}

		// Kanban Column Counters & Placeholders Helpers
		function updateColumnCount(columnEl, offset) {
			var countEl = columnEl.querySelector('.leadite-kanban-column-count');
			if (countEl) {
				var currentCount = parseInt(countEl.textContent, 10) || 0;
				countEl.textContent = Math.max(0, currentCount + offset);
			}
		}

		function checkColumnEmpty(columnEl) {
			var cardsContainer = columnEl.querySelector('.leadite-kanban-column-cards');
			if (!cardsContainer) return;
			var cardElements = cardsContainer.querySelectorAll('.leadite-kanban-card');
			var emptyPlaceholder = cardsContainer.querySelector('.leadite-kanban-empty');

			if (cardElements.length === 0) {
				if (!emptyPlaceholder) {
					var div = document.createElement('div');
					div.className = 'leadite-kanban-empty';
					div.textContent = 'No leads';
					cardsContainer.appendChild(div);
				} else {
					emptyPlaceholder.style.display = 'block';
				}
			} else {
				if (emptyPlaceholder) {
					emptyPlaceholder.style.display = 'none';
				}
			}
		}

		// AJAX Lead Details Modal Controls
		var modal = document.getElementById('leadite-details-modal');
		var contentContainer = modal ? modal.querySelector('.leadite-modal-content') : null;

		function openLeadDetailsModal(leadId) {
			if (!modal || !contentContainer) return;
			modal.style.display = 'flex';
			document.body.classList.add('leadite-modal-open');

			contentContainer.innerHTML = '<div class="leadite-modal-spinner"><div class="leadite-spinner"></div></div>';

			var formData = new FormData();
			formData.append('action', 'leadite_get_lead_details');
			formData.append('security', leaditeAdmin.detailsNonce);
			formData.append('lead_id', leadId);

			fetch(leaditeAdmin.ajaxUrl, {
				method: 'POST',
				body: formData
			})
				.then(function (response) {
					return response.json();
				})
				.then(function (data) {
					if (!data.success) {
						throw new Error(data.data && data.data.message ? data.data.message : 'Load failed');
					}
					contentContainer.innerHTML = data.data.html;

					bindModalNotes(leadId);
					bindModalStatusChanger(leadId);
					bindModalCloseEvents();
				})
				.catch(function (error) {
					// Build error display without innerHTML to prevent XSS from error messages.
					var header = document.createElement('div');
					header.className = 'leadite-modal-header';
					var h2 = document.createElement('h2');
					h2.textContent = 'Error';
					var closeBtn = document.createElement('button');
					closeBtn.type = 'button';
					closeBtn.className = 'leadite-modal-close';
					closeBtn.setAttribute('aria-label', 'Close');
					closeBtn.textContent = '\u00d7';
					header.appendChild(h2);
					header.appendChild(closeBtn);
					var body = document.createElement('div');
					body.className = 'leadite-modal-body';
					var p = document.createElement('p');
					p.textContent = error.message || 'An error occurred';
					body.appendChild(p);
					if (contentContainer) {
						contentContainer.innerHTML = '';
						contentContainer.appendChild(header);
						contentContainer.appendChild(body);
					}
					bindModalCloseEvents();
				});
		}

		function closeModal() {
			if (!modal) return;
			modal.style.display = 'none';
			document.body.classList.remove('leadite-modal-open');
			if (contentContainer) {
				contentContainer.innerHTML = '';
			}
		}

		function bindModalCloseEvents() {
			if (!modal) return;
			var closeBtns = modal.querySelectorAll('.leadite-modal-close');
			closeBtns.forEach(function (btn) {
				btn.addEventListener('click', closeModal);
			});

			var overlay = modal.querySelector('.leadite-modal-overlay');
			if (overlay) {
				overlay.addEventListener('click', closeModal);
			}
		}

		function bindModalNotes(leadId) {
			if (!contentContainer) return;
			var textarea = contentContainer.querySelector('#leadite-note-textarea');
			var button = contentContainer.querySelector('#leadite-add-note-btn');
			var timelineFeed = contentContainer.querySelector('#leadite-timeline-feed');

			if (textarea && button && timelineFeed) {
				button.addEventListener('click', function () {
					var noteText = textarea.value.trim();
					if (!noteText) return;

					textarea.disabled = true;
					button.disabled = true;
					var originalText = button.textContent;
					button.textContent = 'Saving...';

					var formData = new FormData();
					formData.append('action', 'leadite_add_note');
					formData.append('security', leaditeAdmin.noteNonce);
					formData.append('submission_id', leadId);
					formData.append('note', noteText);

					fetch(leaditeAdmin.ajaxUrl, {
						method: 'POST',
						body: formData
					})
						.then(function (response) {
							return response.json();
						})
						.then(function (data) {
							if (!data.success) {
								throw new Error(data.data && data.data.message ? data.data.message : 'Save failed');
							}

							var emptyText = timelineFeed.querySelector('.leadite-timeline-empty');
							if (emptyText) emptyText.remove();

							var tempDiv = document.createElement('div');
							tempDiv.innerHTML = data.data.html;
							var newNoteNode = tempDiv.firstElementChild;
							newNoteNode.classList.add('leadite-timeline-item--new');

							timelineFeed.insertBefore(newNoteNode, timelineFeed.firstChild);
							textarea.value = '';
						})
						.catch(function (error) {
							alert('Error: ' + error.message);
						})
						.finally(function () {
							textarea.disabled = false;
							button.disabled = false;
							button.textContent = originalText;
						});
				});
			}
		}

		function bindModalStatusChanger(leadId) {
			if (!contentContainer) return;
			var select = contentContainer.querySelector('.leadite-status-select-ajax');
			if (select) {
				var form = select.closest('form');
				if (form) {
					form.addEventListener('submit', function (e) {
						e.preventDefault();
					});
					var saveBtn = form.querySelector('input[type="submit"]');
					if (saveBtn) {
						saveBtn.style.display = 'none';
					}
				}

				select.addEventListener('change', function () {
					var newStatus = select.value;
					select.disabled = true;

					var formData = new FormData();
					formData.append('action', 'leadite_update_lead_status');
					formData.append('security', leaditeAdmin.kanbanNonce);
					formData.append('lead_id', leadId);
					formData.append('status', newStatus);

					fetch(leaditeAdmin.ajaxUrl, {
						method: 'POST',
						body: formData
					})
						.then(function (response) {
							return response.json();
						})
						.then(function (data) {
							if (!data.success) {
								throw new Error(data.data && data.data.message ? data.data.message : 'Update failed');
							}
							var card = document.querySelector('.leadite-kanban-card[data-lead-id="' + leadId + '"]');
							var targetColumn = document.querySelector('.leadite-kanban-column[data-status="' + newStatus + '"]');
							if (card && targetColumn) {
								var sourceColumn = card.closest('.leadite-kanban-column');
								var targetCardsContainer = targetColumn.querySelector('.leadite-kanban-column-cards');

								if (sourceColumn && sourceColumn !== targetColumn) {
									updateColumnCount(sourceColumn, -1);
									updateColumnCount(targetColumn, 1);
									targetCardsContainer.appendChild(card);
									checkColumnEmpty(sourceColumn);
									checkColumnEmpty(targetColumn);
								}
							}
						})
						.catch(function (error) {
							alert('Error updating status: ' + error.message);
						})
						.finally(function () {
							select.disabled = false;
						});
				});
			}
		}

		window.addEventListener('keydown', function (e) {
			if (e.key === 'Escape' && modal && modal.style.display === 'flex') {
				closeModal();
			}
		});

		// Kanban Board Drag and Drop
		var kanbanBoard = document.querySelector('.leadite-kanban-board');
		if (kanbanBoard) {
			var cards = kanbanBoard.querySelectorAll('.leadite-kanban-card');
			var columns = kanbanBoard.querySelectorAll('.leadite-kanban-column');
			var draggedCard = null;
			var sourceColumn = null;

			// Intercept click on Kanban cards for details modal
			kanbanBoard.addEventListener('click', function (e) {
				var card = e.target.closest('.leadite-kanban-card');
				if (card) {
					var link = e.target.closest('a');
					if (link && link.getAttribute('href').indexOf('view=') !== -1) {
						e.preventDefault();
					}
					var leadId = card.getAttribute('data-lead-id');
					openLeadDetailsModal(leadId);
				}
			});

			cards.forEach(function (card) {
				card.addEventListener('dragstart', function (e) {
					draggedCard = card;
					sourceColumn = card.closest('.leadite-kanban-column');
					card.classList.add('is-dragging');
					e.dataTransfer.effectAllowed = 'move';
					e.dataTransfer.setData('text/plain', card.getAttribute('data-lead-id'));
				});

				card.addEventListener('dragend', function () {
					card.classList.remove('is-dragging');
					draggedCard = null;
					sourceColumn = null;
				});
			});

			columns.forEach(function (column) {
				var cardsContainer = column.querySelector('.leadite-kanban-column-cards');

				column.addEventListener('dragover', function (e) {
					e.preventDefault();
					e.dataTransfer.dropEffect = 'move';
					return false;
				});

				column.addEventListener('dragenter', function () {
					column.classList.add('is-dragover');
				});

				column.addEventListener('dragleave', function () {
					column.classList.remove('is-dragover');
				});

				column.addEventListener('drop', function (e) {
					e.preventDefault();
					column.classList.remove('is-dragover');

					if (!draggedCard) return;

					var targetStatus = column.getAttribute('data-status');
					var sourceStatus = sourceColumn.getAttribute('data-status');

					if (targetStatus === sourceStatus) return;

					var leadId = draggedCard.getAttribute('data-lead-id');
					var nextSibling = draggedCard.nextElementSibling;

					var emptyPlaceholder = cardsContainer.querySelector('.leadite-kanban-empty');
					if (emptyPlaceholder) {
						emptyPlaceholder.style.display = 'none';
					}
					cardsContainer.appendChild(draggedCard);

					updateColumnCount(sourceColumn, -1);
					updateColumnCount(column, 1);

					checkColumnEmpty(sourceColumn);
					checkColumnEmpty(column);

					var formData = new FormData();
					formData.append('action', 'leadite_update_lead_status');
					formData.append('security', leaditeAdmin.kanbanNonce);
					formData.append('lead_id', leadId);
					formData.append('status', targetStatus);

					fetch(leaditeAdmin.ajaxUrl, {
						method: 'POST',
						body: formData
					})
						.then(function (response) {
							return response.json();
						})
						.then(function (data) {
							if (!data.success) {
								throw new Error(data.data && data.data.message ? data.data.message : 'Update failed');
							}
						})
						.catch(function (error) {
							alert('Error: ' + error.message);
							if (nextSibling) {
								sourceColumn.querySelector('.leadite-kanban-column-cards').insertBefore(draggedCard, nextSibling);
							} else {
								sourceColumn.querySelector('.leadite-kanban-column-cards').appendChild(draggedCard);
							}
							updateColumnCount(sourceColumn, 1);
							updateColumnCount(column, -1);
							checkColumnEmpty(sourceColumn);
							checkColumnEmpty(column);
						});
				});
			});
		}

		// Timeline Notes AJAX submission (for static single lead page view)
		var noteFormCard = document.querySelector('.leadite-timeline-card');
		if (noteFormCard && !noteFormCard.closest('.leadite-modal-body')) {
			var noteTextarea = document.getElementById('leadite-note-textarea');
			var addNoteBtn = document.getElementById('leadite-add-note-btn');
			var timelineFeed = document.getElementById('leadite-timeline-feed');
			var leadId = noteFormCard.getAttribute('data-lead-id');

			if (addNoteBtn && noteTextarea && timelineFeed) {
				addNoteBtn.addEventListener('click', function () {
					var noteText = noteTextarea.value.trim();
					if (!noteText) return;

					noteTextarea.disabled = true;
					addNoteBtn.disabled = true;
					var originalText = addNoteBtn.textContent;
					addNoteBtn.textContent = 'Saving...';

					var formData = new FormData();
					formData.append('action', 'leadite_add_note');
					formData.append('security', leaditeAdmin.noteNonce);
					formData.append('submission_id', leadId);
					formData.append('note', noteText);

					fetch(leaditeAdmin.ajaxUrl, {
						method: 'POST',
						body: formData
					})
						.then(function (response) {
							return response.json();
						})
						.then(function (data) {
							if (!data.success) {
								throw new Error(data.data && data.data.message ? data.data.message : 'Save failed');
							}

							var emptyText = timelineFeed.querySelector('.leadite-timeline-empty');
							if (emptyText) emptyText.remove();

							var tempDiv = document.createElement('div');
							tempDiv.innerHTML = data.data.html;
							var newNoteNode = tempDiv.firstElementChild;
							newNoteNode.classList.add('leadite-timeline-item--new');

							timelineFeed.insertBefore(newNoteNode, timelineFeed.firstChild);
							noteTextarea.value = '';
						})
						.catch(function (error) {
							alert('Error: ' + error.message);
						})
						.finally(function () {
							noteTextarea.disabled = false;
							addNoteBtn.disabled = false;
							addNoteBtn.textContent = originalText;
						});
				});
			}
		}

		// Migration cards loading overlay animation
		var migrationForms = document.querySelectorAll('.leadite-migration-card form');
		migrationForms.forEach(function (form) {
			form.addEventListener('submit', function () {
				var btn = form.querySelector('input[type="submit"]');
				if (btn) {
					btn.value = leaditeAdmin.importingText || 'Importing...';
					btn.style.opacity = '0.7';
					btn.style.cursor = 'not-allowed';
					btn.style.pointerEvents = 'none';
				}
				var card = form.closest('.leadite-migration-card');
				if (card) {
					card.style.position = 'relative';
					var overlay = document.createElement('div');
					overlay.className = 'leadite-migration-overlay';
					overlay.innerHTML = '<div class="leadite-spinner"></div>';
					card.appendChild(overlay);
				}
			});
		});

		// ── Starred toggle ─────────────────────────────────────────────────
		// Uses event delegation so it works in both list view and the modal.
		document.body.addEventListener('click', function (e) {
			var btn = e.target.closest('.leadite-star-btn');
			if (!btn) return;

			var leadId = btn.getAttribute('data-lead-id');
			var nonce = btn.getAttribute('data-nonce');
			var nowStar = btn.classList.contains('is-starred');
			var newStar = !nowStar;

			btn.disabled = true;

			var fd = new FormData();
			fd.append('action', 'leadite_toggle_starred');
			fd.append('security', nonce);
			fd.append('lead_id', leadId);
			fd.append('starred', newStar ? '1' : '0');

			fetch(leaditeAdmin.ajaxUrl, { method: 'POST', body: fd })
				.then(function (r) { return r.json(); })
				.then(function (data) {
					if (!data.success) { throw new Error('Failed'); }
					// Update all star buttons for this lead on the page.
					document.querySelectorAll('.leadite-star-btn[data-lead-id="' + leadId + '"]').forEach(function (b) {
						b.classList.toggle('is-starred', newStar);
						b.textContent = newStar ? '\u2605' : '\u2606';
						var isListBtn = b.classList.contains('leadite-star-btn--list');
						if (!isListBtn) {
							b.textContent = newStar ? '\u2605 ' + (leaditeAdmin.labelStarred || 'Starred') : '\u2606 ' + (leaditeAdmin.labelStar || 'Star this lead');
						}
						b.setAttribute('aria-label', newStar ? (leaditeAdmin.labelUnstar || 'Remove from favourites') : (leaditeAdmin.labelStar || 'Add to favourites'));
					});
				})
				.catch(function () { /* silently keep old state */ })
				.finally(function () { btn.disabled = false; });
		});

		// ── Assign lead ────────────────────────────────────────────────────
		// Dropdown: fires on change.
		document.body.addEventListener('change', function (e) {
			var select = e.target.closest('.leadite-assign-select');
			if (!select) return;

			var leadId = select.getAttribute('data-lead-id');
			var nonce = select.getAttribute('data-nonce');
			var userId = select.value;

			select.disabled = true;

			var fd = new FormData();
			fd.append('action', 'leadite_assign_lead');
			fd.append('security', nonce);
			fd.append('lead_id', leadId);
			fd.append('user_id', userId);

			fetch(leaditeAdmin.ajaxUrl, { method: 'POST', body: fd })
				.then(function (r) { return r.json(); })
				.catch(function () { })
				.finally(function () { select.disabled = false; });
		});

		// "Assign to me" button.
		document.body.addEventListener('click', function (e) {
			var btn = e.target.closest('.leadite-assign-me-btn');
			if (!btn) return;

			var leadId = btn.getAttribute('data-lead-id');
			var userId = btn.getAttribute('data-user-id');
			var nonce = btn.getAttribute('data-nonce');

			btn.disabled = true;

			var fd = new FormData();
			fd.append('action', 'leadite_assign_lead');
			fd.append('security', nonce);
			fd.append('lead_id', leadId);
			fd.append('user_id', userId);

			fetch(leaditeAdmin.ajaxUrl, { method: 'POST', body: fd })
				.then(function (r) { return r.json(); })
				.then(function (data) {
					if (!data.success) { throw new Error('Failed'); }
					// Sync the select to the newly chosen user.
					var select = document.querySelector('.leadite-assign-select[data-lead-id="' + leadId + '"]');
					if (select) { select.value = userId; }
					// Hide the button since user is now assigned to themselves.
					btn.style.display = 'none';
				})
				.catch(function () { })
				.finally(function () { btn.disabled = false; });
		});
		// ── Tags (lead detail card) ────────────────────────────────────
		var tagsCard = document.getElementById('leadite-tags-card');
		if (tagsCard) {
			var leadId = tagsCard.getAttribute('data-lead-id');
			var tagsNonce = tagsCard.getAttribute('data-nonce');
			var chipsWrap = document.getElementById('leadite-tags-chips');
			var addSelect = document.getElementById('leadite-tag-add-select');
			var newNameInput = document.getElementById('leadite-new-tag-name');
			var newColorInput = document.getElementById('leadite-new-tag-color');
			var createBtn = document.getElementById('leadite-create-tag-btn');

			function makeChip(tagId, name, color) {
				var span = document.createElement('span');
				span.className = 'leadite-tag-chip';
				span.setAttribute('data-tag-id', tagId);
				span.style.setProperty('--tag-color', color);

				// Use DOM API — never innerHTML — so tag names cannot inject HTML.
				span.appendChild(document.createTextNode(name));
				span.appendChild(document.createTextNode('\u00a0')); // non-breaking space before button

				var btn = document.createElement('button');
				btn.type = 'button';
				btn.className = 'leadite-tag-remove';
				btn.setAttribute('data-tag-id', tagId);
				btn.setAttribute('aria-label', 'Remove tag');
				btn.textContent = '\u00d7'; // ×
				span.appendChild(btn);

				return span;
			}

			function removeEmpty() {
				var empty = chipsWrap ? chipsWrap.querySelector('.leadite-tags-empty') : null;
				if (empty) empty.remove();
			}

			// Add existing tag from dropdown.
			if (addSelect) {
				addSelect.addEventListener('change', function () {
					var tagId = addSelect.value;
					if (!tagId) return;
					var selectedOption = addSelect.options[addSelect.selectedIndex];
					var color = selectedOption.getAttribute('data-color') || '#6366f1';
					var name = selectedOption.textContent.trim();
					addSelect.disabled = true;

					var fd = new FormData();
					fd.append('action', 'leadite_add_lead_tag');
					fd.append('security', tagsNonce);
					fd.append('lead_id', leadId);
					fd.append('tag_id', tagId);

					fetch(leaditeAdmin.ajaxUrl, { method: 'POST', body: fd })
						.then(function (r) { return r.json(); })
						.then(function (data) {
							if (!data.success) { throw new Error(data.data && data.data.message ? data.data.message : 'Failed'); }
							removeEmpty();
							if (chipsWrap) { chipsWrap.appendChild(makeChip(tagId, name, color)); }
							// Remove from dropdown.
							selectedOption.remove();
							addSelect.value = '';
						})
						.catch(function (err) { alert('Error: ' + err.message); })
						.finally(function () { addSelect.disabled = false; });
				});
			}

			// Remove tag chip.
			document.body.addEventListener('click', function (e) {
				var btn = e.target.closest('.leadite-tag-remove');
				if (!btn || !tagsCard.contains(btn)) return;
				var tagId = btn.getAttribute('data-tag-id');
				btn.disabled = true;

				var fd = new FormData();
				fd.append('action', 'leadite_remove_lead_tag');
				fd.append('security', tagsNonce);
				fd.append('lead_id', leadId);
				fd.append('tag_id', tagId);

				fetch(leaditeAdmin.ajaxUrl, { method: 'POST', body: fd })
					.then(function (r) { return r.json(); })
					.then(function (data) {
						if (!data.success) { throw new Error(data.data && data.data.message ? data.data.message : 'Failed'); }
						var chip = btn.closest('.leadite-tag-chip');
						var chipName = chip ? chip.textContent.trim() : '';
						var chipColor = chip ? chip.style.getPropertyValue('--tag-color') : '#6366f1';
						if (chip) chip.remove();
						// Re-add to dropdown if it exists.
						if (addSelect && tagId) {
							var opt = document.createElement('option');
							opt.value = tagId;
							opt.setAttribute('data-color', chipColor);
							opt.textContent = chipName;
							addSelect.appendChild(opt);
						}
						if (chipsWrap && !chipsWrap.querySelector('.leadite-tag-chip')) {
							var emptySpan = document.createElement('span');
							emptySpan.className = 'leadite-tags-empty';
							emptySpan.textContent = 'No tags yet.';
							chipsWrap.appendChild(emptySpan);
						}
					})
					.catch(function (err) { alert('Error: ' + err.message); })
					.finally(function () { btn.disabled = false; });
			});

			// Create & add new tag.
			if (createBtn && newNameInput && newColorInput) {
				createBtn.addEventListener('click', function () {
					var name = newNameInput.value.trim();
					var color = newColorInput.value || '#6366f1';
					if (!name) { newNameInput.focus(); return; }
					createBtn.disabled = true;

					var fd = new FormData();
					fd.append('action', 'leadite_create_tag');
					fd.append('security', tagsNonce);
					fd.append('lead_id', leadId);
					fd.append('name', name);
					fd.append('color', color);

					fetch(leaditeAdmin.ajaxUrl, { method: 'POST', body: fd })
						.then(function (r) { return r.json(); })
						.then(function (data) {
							if (!data.success) { throw new Error(data.data && data.data.message ? data.data.message : 'Failed'); }
							removeEmpty();
							if (chipsWrap) { chipsWrap.appendChild(makeChip(data.data.tag_id, name, color)); }
							newNameInput.value = '';
							newColorInput.value = '#6366f1';
						})
						.catch(function (err) { alert('Error: ' + err.message); })
						.finally(function () { createBtn.disabled = false; });
				});
				// Allow Enter key on name input.
				newNameInput.addEventListener('keydown', function (e) {
					if (e.key === 'Enter') { e.preventDefault(); createBtn.click(); }
				});
			}
		}

		// ── Tags management (Settings → Pro tab) ──────────────────────
		var settingsCreateBtn = document.getElementById('leadite-settings-create-tag-btn');
		if (settingsCreateBtn) {
			var settingsNonce = settingsCreateBtn.getAttribute('data-nonce');
			var settingsNameInput = document.getElementById('leadite-settings-new-tag-name');
			var settingsColorInput = document.getElementById('leadite-settings-new-tag-color');

			settingsCreateBtn.addEventListener('click', function () {
				var name = settingsNameInput ? settingsNameInput.value.trim() : '';
				var color = settingsColorInput ? (settingsColorInput.value || '#6366f1') : '#6366f1';
				if (!name) { if (settingsNameInput) settingsNameInput.focus(); return; }
				settingsCreateBtn.disabled = true;

				var fd = new FormData();
				fd.append('action', 'leadite_create_tag');
				fd.append('security', settingsNonce);
				fd.append('name', name);
				fd.append('color', color);

				fetch(leaditeAdmin.ajaxUrl, { method: 'POST', body: fd })
					.then(function (r) { return r.json(); })
					.then(function (data) {
						if (!data.success) { throw new Error(data.data && data.data.message ? data.data.message : 'Failed'); }
						// Reload the page to refresh the tags table.
						window.location.reload();
					})
					.catch(function (err) { alert('Error: ' + err.message); })
					.finally(function () { settingsCreateBtn.disabled = false; });
			});

			if (settingsNameInput) {
				settingsNameInput.addEventListener('keydown', function (e) {
					if (e.key === 'Enter') { e.preventDefault(); settingsCreateBtn.click(); }
				});
			}
		}

		// Delete tag from settings page.
		document.body.addEventListener('click', function (e) {
			var btn = e.target.closest('.leadite-delete-tag-btn');
			if (!btn) return;
			if (!window.confirm(leaditeAdmin.confirmDeleteTag || 'Delete this tag? It will be removed from all leads.')) return;
			var tagId = btn.getAttribute('data-tag-id');
			var nonce = btn.getAttribute('data-nonce');
			btn.disabled = true;

			var fd = new FormData();
			fd.append('action', 'leadite_delete_tag');
			fd.append('security', nonce);
			fd.append('tag_id', tagId);

			fetch(leaditeAdmin.ajaxUrl, { method: 'POST', body: fd })
				.then(function (r) { return r.json(); })
				.then(function (data) {
					if (!data.success) { throw new Error(data.data && data.data.message ? data.data.message : 'Failed'); }
					var row = btn.closest('tr');
					if (row) { row.remove(); }
				})
				.catch(function (err) { alert('Error: ' + err.message); })
				.finally(function () { btn.disabled = false; });
		});

		// ── Batch IP anonymization ─────────────────────────────────────
		var batchAnonBtn = document.getElementById('leadite-batch-anonymize-btn');
		if (batchAnonBtn) {
			var batchStatus = document.getElementById('leadite-batch-anonymize-status');
			batchAnonBtn.addEventListener('click', function () {
				if (!window.confirm('This will permanently anonymize all stored IP addresses in your leads. This action cannot be undone. Continue?')) {
					return;
				}
				var nonce = batchAnonBtn.getAttribute('data-nonce');
				batchAnonBtn.disabled = true;
				if (batchStatus) { batchStatus.textContent = 'Processing...'; }

				function runBatch() {
					var fd = new FormData();
					fd.append('action', 'leadite_batch_anonymize_ip');
					fd.append('security', nonce);

					fetch(leaditeAdmin.ajaxUrl, { method: 'POST', body: fd })
						.then(function (r) { return r.json(); })
						.then(function (data) {
							if (!data.success) {
								throw new Error(data.data && data.data.message ? data.data.message : 'Failed');
							}
							if (data.data.remaining > 0) {
								if (batchStatus) {
									batchStatus.textContent = 'Processed ' + data.data.processed + ' this batch, ' + data.data.remaining + ' remaining...';
								}
								runBatch(); // Next batch.
							} else {
								if (batchStatus) { batchStatus.textContent = '\u2714 Done. All stored IPs have been anonymized.'; }
								batchAnonBtn.disabled = false;
							}
						})
						.catch(function (err) {
							if (batchStatus) { batchStatus.textContent = 'Error: ' + err.message; }
							batchAnonBtn.disabled = false;
						});
				}

				runBatch();
			});
		}

		// ── Send Test Digest AJAX ──────────────────────────────────────
		var testDigestBtn = document.getElementById('leadite-send-test-digest');
		if (testDigestBtn) {
			var testDigestFeedback = document.getElementById('leadite-test-digest-feedback');
			var testDigestEmailInput = document.getElementById('lh_followup_digest_email');

			testDigestBtn.addEventListener('click', function () {
				var emailVal = testDigestEmailInput ? testDigestEmailInput.value.trim() : '';

				testDigestBtn.disabled = true;
				if (testDigestFeedback) {
					testDigestFeedback.textContent = 'Sending...';
					testDigestFeedback.style.color = '#475569';
				}

				var fd = new FormData();
				fd.append('action', 'leadite_send_test_digest');
				fd.append('security', leaditeAdmin.testDigestNonce);
				fd.append('email', emailVal);

				fetch(leaditeAdmin.ajaxUrl, { method: 'POST', body: fd })
					.then(function (r) { return r.json(); })
					.then(function (data) {
						if (!data.success) {
							throw new Error(data.data && data.data.message ? data.data.message : 'Failed');
						}
						if (testDigestFeedback) {
							testDigestFeedback.textContent = '\u2714 ' + (data.data.message || 'Sent!');
							testDigestFeedback.style.color = '#10b981';
						}
					})
					.catch(function (err) {
						if (testDigestFeedback) {
							testDigestFeedback.textContent = '\u2717 ' + err.message;
							testDigestFeedback.style.color = '#ef4444';
						}
					})
					.finally(function () {
						testDigestBtn.disabled = false;
					});
			});
		}

		// ── Copy Code Block Button ────────────────────────────────────
		document.body.addEventListener('click', function (e) {
			var btn = e.target.closest('.leadite-copy-code-btn');
			if (!btn) return;

			var wrapper = btn.closest('.leadite-code-block-wrapper');
			if (!wrapper) return;

			var codeBlock = wrapper.querySelector('.leadite-code-block');
			if (!codeBlock) return;

			var text = codeBlock.textContent || codeBlock.innerText;

			// Clipboard API
			if (navigator.clipboard && navigator.clipboard.writeText) {
				navigator.clipboard.writeText(text).then(showSuccess, showError);
			} else {
				// Fallback
				var textarea = document.createElement('textarea');
				textarea.value = text;
				textarea.style.position = 'fixed';
				document.body.appendChild(textarea);
				textarea.select();
				try {
					document.execCommand('copy');
					showSuccess();
				} catch (err) {
					showError();
				}
				document.body.removeChild(textarea);
			}

			function showSuccess() {
				var originalText = btn.textContent;
				btn.textContent = leaditeAdmin.copiedText || 'Copied!';
				btn.style.borderColor = '#10b981';
				btn.style.color = '#10b981';
				setTimeout(function () {
					btn.textContent = originalText;
					btn.style.borderColor = '';
					btn.style.color = '';
				}, 2000);
			}

			function showError() {
				var originalText = btn.textContent;
				btn.textContent = leaditeAdmin.copiedErrorText || 'Error!';
				btn.style.borderColor = '#ef4444';
				btn.style.color = '#ef4444';
				setTimeout(function () {
					btn.textContent = originalText;
					btn.style.borderColor = '';
					btn.style.color = '';
				}, 2000);
			}
		});

	});
})();