(function () {
	'use strict';

	document.querySelectorAll('.cm-scan-form, .cm-idea-layout form').forEach(function (form) {
		form.addEventListener('submit', function () {
			var button = form.querySelector('button[type="submit"]');
			if (!button) {
				return;
			}

			button.disabled = true;
			button.textContent = form.classList.contains('cm-memory-form') ? 'Starting sync…' : (form.classList.contains('cm-scan-form') ? 'Mining content…' : 'Checking inventory…');
		});
	});

	function copyText(text) {
		if (navigator.clipboard && navigator.clipboard.writeText) {
			return navigator.clipboard.writeText(text);
		}
		return new Promise(function (resolve, reject) {
			var fallback = document.createElement('textarea');
			fallback.value = text;
			fallback.setAttribute('readonly', 'readonly');
			fallback.style.position = 'fixed';
			fallback.style.opacity = '0';
			document.body.appendChild(fallback);
			fallback.select();
			try {
				if (!document.execCommand('copy')) {
					throw new Error('Copy command failed.');
				}
				resolve();
			} catch (error) {
				reject(error);
			} finally {
				fallback.remove();
			}
		});
	}

	document.querySelectorAll('.cm-copy-prompt').forEach(function (button) {
		button.addEventListener('click', function () {
			var source = document.getElementById(button.getAttribute('data-prompt-target'));
			var confirmation = button.closest('.cm-ai-tools').querySelector('.cm-copy-confirmation');
			if (!source) {
				return;
			}
			copyText(source.value).then(function () {
				confirmation.textContent = window.contentMinerPrompts ? window.contentMinerPrompts.copied : 'Copied';
				window.setTimeout(function () { confirmation.textContent = ''; }, 5000);
			}).catch(function () {
				confirmation.textContent = window.contentMinerPrompts ? window.contentMinerPrompts.copyFailed : 'Copy failed';
			});
		});
	});

	var sectionNav = document.querySelector('[data-cm-section-nav]');
	if (sectionNav) {
		var sectionTabs = Array.prototype.slice.call(sectionNav.querySelectorAll('a[aria-controls]'));
		var sections = sectionTabs.map(function (tab) {
			return document.getElementById(tab.getAttribute('aria-controls'));
		}).filter(Boolean);

		function sectionForHash(hash) {
			var target = hash ? document.getElementById(hash.replace(/^#/, '')) : null;
			return target ? target.closest('[data-cm-section]') : null;
		}

		function activateSection(section) {
			var activeSection = section || document.getElementById('overview');
			sections.forEach(function (candidate) {
				var isActive = candidate === activeSection;
				candidate.hidden = !isActive;
				var tab = sectionNav.querySelector('[aria-controls="' + candidate.id + '"]');
				if (tab) {
					tab.setAttribute('aria-selected', isActive ? 'true' : 'false');
					tab.setAttribute('tabindex', isActive ? '0' : '-1');
				}
			});
		}

		sectionTabs.forEach(function (tab) {
			tab.addEventListener('click', function () {
				activateSection(document.getElementById(tab.getAttribute('aria-controls')));
			});
			tab.addEventListener('keydown', function (event) {
				var currentIndex = sectionTabs.indexOf(tab);
				var nextIndex = currentIndex;
				if ('ArrowRight' === event.key) {
					nextIndex = (currentIndex + 1) % sectionTabs.length;
				} else if ('ArrowLeft' === event.key) {
					nextIndex = (currentIndex - 1 + sectionTabs.length) % sectionTabs.length;
				} else if ('Home' === event.key) {
					nextIndex = 0;
				} else if ('End' === event.key) {
					nextIndex = sectionTabs.length - 1;
				} else {
					return;
				}
				event.preventDefault();
				sectionTabs[nextIndex].focus();
				sectionTabs[nextIndex].click();
			});
		});
		window.addEventListener('hashchange', function () {
			activateSection(sectionForHash(window.location.hash));
		});
		activateSection(sectionForHash(window.location.hash));
	}

	var inventoryExpand = document.querySelector('[data-cm-inventory-expand]');
	if (inventoryExpand) {
		var deferredInventoryRows = Array.prototype.slice.call(document.querySelectorAll('.cm-inventory-row--deferred'));
		function revealInventoryRows() {
			deferredInventoryRows.forEach(function (row) {
				row.hidden = false;
			});
			inventoryExpand.setAttribute('aria-expanded', 'true');
			inventoryExpand.parentNode.hidden = true;
		}
		inventoryExpand.addEventListener('click', revealInventoryRows);
		var anchoredRow = window.location.hash ? document.getElementById(window.location.hash.replace(/^#/, '')) : null;
		if (anchoredRow && anchoredRow.classList.contains('cm-inventory-row--deferred')) {
			revealInventoryRows();
		}
	}

	var activePipeline = document.querySelector('[data-cm-pipeline-active="1"]');
	if (activePipeline) {
		(function refreshActivePipeline() {
			window.setTimeout(function () {
				if (!document.querySelector('[data-cm-pipeline-active="1"]')) {
					return;
				}
				if (document.hidden) {
					refreshActivePipeline();
					return;
				}
				if (!window.contentMinerPipeline || !window.contentMinerPipeline.ajaxUrl || !window.contentMinerPipeline.nonce) {
					window.location.reload();
					return;
				}
				var body = new window.URLSearchParams();
				body.set('action', 'content_miner_pipeline_tick');
				body.set('nonce', window.contentMinerPipeline.nonce);
				window.fetch(window.contentMinerPipeline.ajaxUrl, {
					method: 'POST',
					credentials: 'same-origin',
					headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
					body: body.toString()
				}).then(function () {
					window.location.reload();
				}).catch(function () {
					refreshActivePipeline();
				});
			}, (window.contentMinerPipeline && window.contentMinerPipeline.intervalMs) || 3000);
		}());
	}

	function trackConsultation(eventName, cta) {
		window.dataLayer = window.dataLayer || [];
		window.dataLayer.push({
			event: eventName,
			content_miner_context: cta.getAttribute('data-cta-context') || '',
			content_miner_source: cta.getAttribute('data-cta-source') || ''
		});
	}

	var consultationDismissed = false;
	try {
		consultationDismissed = '1' === window.sessionStorage.getItem('contentMinerConsultationDismissed');
	} catch (error) {
		consultationDismissed = false;
	}
	document.querySelectorAll('.cm-consultation-cta').forEach(function (cta) {
		if (consultationDismissed) {
			cta.hidden = true;
			return;
		}
		trackConsultation('content_miner_consultation_cta_view', cta);
		var link = cta.querySelector('a');
		var dismiss = cta.querySelector('.cm-consultation-dismiss');
		if (link) {
			link.addEventListener('click', function () {
				trackConsultation('content_miner_consultation_cta_click', cta);
			});
		}
		if (dismiss) {
			dismiss.addEventListener('click', function () {
				document.querySelectorAll('.cm-consultation-cta').forEach(function (item) { item.hidden = true; });
				try { window.sessionStorage.setItem('contentMinerConsultationDismissed', '1'); } catch (error) {}
			});
		}
	});
}());
