(function () {
	'use strict';

	function initTabs() {
		const tabs = document.querySelectorAll('[data-replyan-ai-tab]');
		const panels = document.querySelectorAll('[data-replyan-ai-panel]');

		tabs.forEach((tab) => {
			tab.addEventListener('click', () => {
				const target = tab.getAttribute('data-replyan-ai-tab');

				tabs.forEach((item) => {
					const isActive = item === tab;
					item.classList.toggle('nav-tab-active', isActive);
					item.setAttribute('aria-selected', isActive ? 'true' : 'false');
				});

				panels.forEach((panel) => {
					const isActive = panel.getAttribute('data-replyan-ai-panel') === target;
					panel.classList.toggle('is-active', isActive);
					panel.hidden = !isActive;
				});
			});
		});
	}

	function initRangeOutputs() {
		document.querySelectorAll('.replyan-ai-range-field input[type="range"]').forEach((range) => {
			const output = range.nextElementSibling;

			if (!output) {
				return;
			}

			range.addEventListener('input', () => {
				output.value = range.value;
			});
		});
	}

	function initApiKeyControls() {
		document.querySelectorAll('.replyan-ai-api-key-card').forEach((card) => {
			const toggle = card.querySelector('.replyan-ai-switch input');
			const status = card.querySelector('[data-replyan-ai-api-status]');
			const deleteButton = card.querySelector('[data-replyan-ai-delete-key]');
			const deleteInput = card.querySelector('[data-replyan-ai-delete-key-input]');

			if (toggle && status) {
				toggle.addEventListener('change', () => {
					card.classList.toggle('is-enabled', toggle.checked);
					card.classList.toggle('is-disabled', !toggle.checked);
					status.textContent = toggle.checked
						? 'Enabled and ready to use'
						: 'Disabled. Enable it when you want the chatbot to answer.';
				});
			}

			if (deleteButton && deleteInput && status) {
				deleteButton.addEventListener('click', () => {
					deleteInput.value = '1';
					card.classList.add('is-delete-pending');
					status.textContent = 'Will be deleted when you click Save Changes.';

					if (toggle) {
						toggle.checked = false;
						toggle.disabled = true;
					}

					deleteButton.disabled = true;
				});
			}
		});
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', () => {
			initTabs();
			initRangeOutputs();
			initApiKeyControls();
		});
	} else {
		initTabs();
		initRangeOutputs();
		initApiKeyControls();
	}
})();
