/* global window, document */
(function (window, document) {
	'use strict';

	const app = window.MailDoctorAdminApp;

	if (!app) {
		return;
	}

	const PROVIDER_TRANSPORT_MAP = {
		'mail': 'mail',
		'brevo': 'smtp',
		'gmail': 'smtp',
		'outlook': 'smtp',
		'sendgrid': 'sendgrid_api',
		'mailgun': 'mailgun_api',
		'ses': 'ses_api',
		'postmark': 'postmark_api',
		'sparkpost': 'sparkpost_api',
		'smtp': 'smtp'
	};

	function updateProviderVisibility(selectedProvider) {
		const rows = document.querySelectorAll('.mail-doctor-provider-row');
		if (!rows.length) {
			return;
		}

		rows.forEach((row) => {
			let show = false;
			if (row.classList.contains('mail-doctor-provider-smtp-details')) {
				show = (selectedProvider === 'smtp');
			} else if (row.classList.contains('mail-doctor-provider-smtp-credentials')) {
				show = ['smtp', 'brevo', 'gmail', 'outlook'].includes(selectedProvider);
			} else if (row.classList.contains('mail-doctor-provider-mailgun')) {
				show = (selectedProvider === 'mailgun');
			} else if (row.classList.contains('mail-doctor-provider-sendgrid')) {
				show = (selectedProvider === 'sendgrid');
			} else if (row.classList.contains('mail-doctor-provider-postmark')) {
				show = (selectedProvider === 'postmark');
			} else if (row.classList.contains('mail-doctor-provider-sparkpost')) {
				show = (selectedProvider === 'sparkpost');
			} else if (row.classList.contains('mail-doctor-provider-ses')) {
				show = (selectedProvider === 'ses');
			} else if (row.classList.contains('mail-doctor-provider-generic')) {
				show = (selectedProvider === 'generic');
			} else if (row.classList.contains('mail-doctor-provider-all')) {
				show = (selectedProvider !== 'mail');
			}
			row.hidden = !show;
			row.style.display = show ? '' : 'none';
			row.setAttribute('aria-hidden', show ? 'false' : 'true');
		});

		// Dynamic labels/placeholders
		const usernameLabel = document.getElementById('mail-doctor-username-label');
		const usernameInput = document.getElementById('mail-doctor-username');
		const usernameDesc = document.getElementById('mail-doctor-username-desc');

		const passwordLabel = document.getElementById('mail-doctor-password-label');
		const passwordInput = document.getElementById('mail-doctor-password');
		const passwordDesc = document.getElementById('mail-doctor-password-desc');

		if (selectedProvider === 'brevo') {
			if (usernameLabel) usernameLabel.textContent = 'Brevo SMTP Username';
			if (usernameInput) usernameInput.placeholder = 'e.g. brevo-account-email@domain.com';
			if (usernameDesc) usernameDesc.textContent = 'Enter your Brevo SMTP login username (usually your Brevo account email address).';
			
			if (passwordLabel) passwordLabel.textContent = 'Brevo SMTP Password (SMTP Key)';
			if (passwordDesc) passwordDesc.textContent = 'Enter your Brevo SMTP key (password). Note: This is NOT your standard Brevo API key. You can find/generate it in your Brevo account under SMTP & API > SMTP tab.';

			const fromEmailVal = document.getElementById('mail-doctor-from-email') ? document.getElementById('mail-doctor-from-email').value : '';
			if (usernameInput && !usernameInput.value && fromEmailVal) {
				usernameInput.value = fromEmailVal;
			}
		} else if (selectedProvider === 'gmail') {
			if (usernameLabel) usernameLabel.textContent = 'Gmail Username';
			if (usernameInput) usernameInput.placeholder = 'e.g. username@gmail.com';
			if (usernameDesc) usernameDesc.textContent = 'Enter your Google account email address.';
			
			if (passwordLabel) passwordLabel.textContent = 'Google App Password';
			if (passwordDesc) passwordDesc.textContent = 'Enter your Google App Password (not your primary password).';

			const fromEmailVal = document.getElementById('mail-doctor-from-email') ? document.getElementById('mail-doctor-from-email').value : '';
			if (usernameInput && !usernameInput.value && fromEmailVal) {
				usernameInput.value = fromEmailVal;
			}
		} else if (selectedProvider === 'outlook') {
			if (usernameLabel) usernameLabel.textContent = 'Outlook Username';
			if (usernameInput) usernameInput.placeholder = 'e.g. username@outlook.com';
			if (usernameDesc) usernameDesc.textContent = 'Enter your Microsoft/Outlook email address.';
			
			if (passwordLabel) passwordLabel.textContent = 'Outlook Password';
			if (passwordDesc) passwordDesc.textContent = 'Enter your Microsoft/Outlook password.';

			const fromEmailVal = document.getElementById('mail-doctor-from-email') ? document.getElementById('mail-doctor-from-email').value : '';
			if (usernameInput && !usernameInput.value && fromEmailVal) {
				usernameInput.value = fromEmailVal;
			}
		} else {
			// Generic SMTP
			if (usernameLabel) usernameLabel.textContent = 'SMTP Username';
			if (usernameInput) usernameInput.placeholder = 'e.g. username';
			if (usernameDesc) usernameDesc.textContent = 'The SMTP login username credential provided by your host.';
			
			if (passwordLabel) passwordLabel.textContent = 'SMTP Password';
			if (passwordDesc) passwordDesc.textContent = 'The SMTP account password or API secret key credential.';
		}

		// Dynamically prefill SMTP connection details for presets
		const hostInput = document.getElementById('mail-doctor-host');
		const portInput = document.getElementById('mail-doctor-port');
		const encryptionSelect = document.getElementById('mail-doctor-encryption');
		const authSelect = document.getElementById('mail-doctor-auth');

		if (selectedProvider === 'brevo') {
			if (hostInput) hostInput.value = 'smtp-relay.brevo.com';
			if (portInput) portInput.value = '587';
			if (encryptionSelect) encryptionSelect.value = 'tls';
			if (authSelect) authSelect.value = 'login';
		} else if (selectedProvider === 'gmail') {
			if (hostInput) hostInput.value = 'smtp.gmail.com';
			if (portInput) portInput.value = '587';
			if (encryptionSelect) encryptionSelect.value = 'tls';
			if (authSelect) authSelect.value = 'login';
		} else if (selectedProvider === 'outlook') {
			if (hostInput) hostInput.value = 'smtp.office365.com';
			if (portInput) portInput.value = '587';
			if (encryptionSelect) encryptionSelect.value = 'tls';
			if (authSelect) authSelect.value = 'login';
		} else if (selectedProvider === 'smtp') {
			if (hostInput) hostInput.value = hostInput.getAttribute('data-original') || '';
			if (portInput) portInput.value = portInput.getAttribute('data-original') || '587';
			if (encryptionSelect) encryptionSelect.value = encryptionSelect.getAttribute('data-original') || 'tls';
			if (authSelect) authSelect.value = authSelect.getAttribute('data-original') || 'login';
		}

		// Update default php mail notice
		const defaultMailNotice = document.getElementById('mail-doctor-default-mail-notice');
		if (defaultMailNotice) {
			const showNotice = (selectedProvider === 'mail');
			defaultMailNotice.style.display = showNotice ? 'block' : 'none';
			defaultMailNotice.setAttribute('aria-hidden', showNotice ? 'false' : 'true');
		}

		// Sync hidden transport input value
		const transportInput = document.getElementById('mail-doctor-transport');
		if (transportInput) {
			transportInput.value = PROVIDER_TRANSPORT_MAP[selectedProvider] || 'mail';
		}

		// Sync hidden provider input value (for AJAX test connection / test email)
		const providerInput = document.getElementById('mail-doctor-provider');
		if (providerInput) {
			providerInput.value = selectedProvider;
		}

		// Update connection details hint text and links
		if (typeof window.mailDoctorProvidersData !== 'undefined' && window.mailDoctorProvidersData[selectedProvider]) {
			const providerData = window.mailDoctorProvidersData[selectedProvider];
			
			const mailerNameEl = document.getElementById('mail-doctor-selected-mailer-name');
			if (mailerNameEl) {
				mailerNameEl.textContent = providerData.label;
			}
			
			const mailerLinkEl = document.getElementById('mail-doctor-selected-mailer-link');
			if (mailerLinkEl) {
				if (providerData.service_link) {
					mailerLinkEl.href = providerData.service_link;
					mailerLinkEl.style.display = 'inline-block';
				} else {
					mailerLinkEl.style.display = 'none';
				}
			}
			
			const mailerDocEl = document.getElementById('mail-doctor-selected-mailer-doc');
			if (mailerDocEl) {
				if (providerData.doc_link) {
					mailerDocEl.href = providerData.doc_link;
					mailerDocEl.style.display = 'inline-block';
					// Add margin if service link is shown
					mailerDocEl.style.marginLeft = providerData.service_link ? '12px' : '0';
				} else {
					mailerDocEl.style.display = 'none';
				}
			}
		}

		// Sync cards active state
		const cards = document.querySelectorAll('.mail-doctor-provider-card');
		cards.forEach((card) => {
			const radio = card.querySelector('input[type="radio"]');
			if (radio) {
				const isChecked = (radio.value === selectedProvider);
				card.classList.toggle('is-active', isChecked);
				radio.checked = isChecked;
			}
		});
	}

	function initProviderSwitching() {
		const cards = document.querySelectorAll('.mail-doctor-provider-card');
		if (!cards.length) {
			return;
		}

		// Save custom values as originals on page load
		const hostInput = document.getElementById('mail-doctor-host');
		const portInput = document.getElementById('mail-doctor-port');
		const encryptionSelect = document.getElementById('mail-doctor-encryption');
		const authSelect = document.getElementById('mail-doctor-auth');

		// Only store if the current saved provider is actually 'smtp' (Generic SMTP), otherwise they are presets.
		const checkedRadio = document.querySelector('input[type="radio"][name="mail_doctor_settings[provider]"]:checked');
		const initialProvider = checkedRadio ? checkedRadio.value : 'mail';

		if (initialProvider === 'smtp') {
			if (hostInput) hostInput.setAttribute('data-original', hostInput.value);
			if (portInput) portInput.setAttribute('data-original', portInput.value);
			if (encryptionSelect) encryptionSelect.setAttribute('data-original', encryptionSelect.value);
			if (authSelect) authSelect.setAttribute('data-original', authSelect.value);
		} else {
			// If loaded with a preset, default original values to empty or standard settings
			if (hostInput) hostInput.setAttribute('data-original', '');
			if (portInput) portInput.setAttribute('data-original', '587');
			if (encryptionSelect) encryptionSelect.setAttribute('data-original', 'tls');
			if (authSelect) authSelect.setAttribute('data-original', 'login');
		}

		// Add change listeners to update backup when generic SMTP is modified
		const updateBackup = () => {
			const activeRadio = document.querySelector('input[type="radio"][name="mail_doctor_settings[provider]"]:checked');
			if (activeRadio && activeRadio.value === 'smtp') {
				if (hostInput) hostInput.setAttribute('data-original', hostInput.value);
				if (portInput) portInput.setAttribute('data-original', portInput.value);
				if (encryptionSelect) encryptionSelect.setAttribute('data-original', encryptionSelect.value);
				if (authSelect) authSelect.setAttribute('data-original', authSelect.value);
			}
		};

		if (hostInput) hostInput.addEventListener('input', updateBackup);
		if (portInput) portInput.addEventListener('input', updateBackup);
		if (encryptionSelect) encryptionSelect.addEventListener('change', updateBackup);
		if (authSelect) authSelect.addEventListener('change', updateBackup);

		cards.forEach((card) => {
			card.addEventListener('click', (e) => {
				const radio = card.querySelector('input[type="radio"]');
				if (radio) {
					updateProviderVisibility(radio.value);
				}
			});
		});

		updateProviderVisibility(initialProvider);
	}

		function activateIntegration(target, container) {
			if (!target || !container) {
				return;
			}

			const tabs = Array.prototype.slice.call(container.querySelectorAll('[data-mail-doctor-integrations-target]'));
			const panes = Array.prototype.slice.call(container.querySelectorAll('.mail-doctor-integrations__pane'));

			tabs.forEach((tab) => {
				const isActive = tab.getAttribute('data-mail-doctor-integrations-target') === target;
				tab.classList.toggle('is-active', isActive);
				tab.setAttribute('aria-selected', isActive ? 'true' : 'false');
			});

			panes.forEach((pane) => {
				const paneId = `mail-doctor-integrations-pane-${target}`;
				const isActive = pane.id === paneId;
				pane.classList.toggle('is-active', isActive);
				pane.hidden = !isActive;
				pane.setAttribute('aria-hidden', isActive ? 'false' : 'true');
				pane.classList.toggle('is-active', isActive);
			});
		}

	function initIntegrationsTabs() {
		const container = document.querySelector('[data-mail-doctor-integrations]');
		if (!container) {
			return;
		}

		const tabs = Array.prototype.slice.call(container.querySelectorAll('[data-mail-doctor-integrations-target]'));
		const initial = tabs.length ? tabs[0].getAttribute('data-mail-doctor-integrations-target') : '';

		container.addEventListener('click', (event) => {
			const tab = event.target.closest('[data-mail-doctor-integrations-target]');
			if (!tab || !container.contains(tab)) {
				return;
			}

			event.preventDefault();
			activateIntegration(tab.getAttribute('data-mail-doctor-integrations-target'), container);
		});

		activateIntegration(initial, container);
	}

	function initWooOverrides() {
		const table = document.querySelector('[data-mail-doctor-woo-table]');
		if (!table) {
			return;
		}

		const checkboxes = Array.prototype.slice.call(table.querySelectorAll('input[type="checkbox"][data-mail-doctor-woo-toggle]'));
		if (!checkboxes.length) {
			return;
		}

		function setAll(state) {
			checkboxes.forEach((box) => {
				box.checked = state;
			});
		}

		table.addEventListener('click', (event) => {
			const action = event.target && event.target.getAttribute('data-mail-doctor-woo-action');
			if (!action) {
				return;
			}

			event.preventDefault();
			const confirmEnable = table.getAttribute('data-confirm-enable');
			const confirmDisable = table.getAttribute('data-confirm-disable');
			const confirmMatch = table.getAttribute('data-confirm-match');

			if (action === 'enable') {
				if (confirmEnable && !window.confirm(confirmEnable)) {
					return;
				}
				setAll(true);
				return;
			}

			if (action === 'disable') {
				if (confirmDisable && !window.confirm(confirmDisable)) {
					return;
				}
				setAll(false);
				return;
			}

			if (action === 'match') {
				if (confirmMatch && !window.confirm(confirmMatch)) {
					return;
				}
				checkboxes.forEach((box) => {
					const defaultState = box.getAttribute('data-mail-doctor-woo-default');
					box.checked = defaultState === '1';
				});
			}
		});
	}

	function initTabLayouts() {
		const menus = Array.prototype.slice.call(document.querySelectorAll('[data-mail-doctor-tab-menu]'));
		if (!menus.length) {
			return;
		}

		menus.forEach((menu) => {
			menu.addEventListener('click', (event) => {
				const trigger = event.target.closest('[data-mail-doctor-tab-target]');
				if (!trigger || !menu.contains(trigger)) {
					return;
				}

				event.preventDefault();

				const target = trigger.getAttribute('data-mail-doctor-tab-target');
				const container = menu.closest('.mail-doctor-tab-layout');
				if (!container || !target) {
					return;
				}

				const tabs = Array.prototype.slice.call(menu.querySelectorAll('[data-mail-doctor-tab-target]'));
				const panels = Array.prototype.slice.call(container.querySelectorAll('[data-mail-doctor-tab-panel]'));

				tabs.forEach((tab) => {
					const active = tab.getAttribute('data-mail-doctor-tab-target') === target;
					tab.classList.toggle('is-active', active);
					tab.setAttribute('aria-selected', active ? 'true' : 'false');
				});

				panels.forEach((panel) => {
					const active = panel.getAttribute('data-mail-doctor-tab-panel') === target;
					panel.hidden = !active;
					panel.setAttribute('aria-hidden', active ? 'false' : 'true');
					panel.classList.toggle('is-active', active);
				});
			});
		});
	}

	function initSettingsNavToggle() {
		const toggle = document.querySelector('.mail-doctor-settings-nav__toggle');
		const list = document.getElementById('mail-doctor-settings-nav-list');

		if (!toggle || !list) {
			return;
		}

		const sync = (expanded) => {
			list.hidden = !expanded;
			toggle.setAttribute('aria-expanded', expanded ? 'true' : 'false');
		};

		toggle.addEventListener('click', () => {
			const expanded = toggle.getAttribute('aria-expanded') === 'true';
			sync(!expanded);
		});

		sync(toggle.getAttribute('aria-expanded') === 'true');
	}

	app.register(() => {
		initProviderSwitching();
		initIntegrationsTabs();
		initTabLayouts();
		initSettingsNavToggle();
		initWooOverrides();
	});
})(window, document);
