(function () {
	function qs(s, c) {
		return (c || document).querySelector(s);
	}
	function qsa(s, c) {
		return Array.prototype.slice.call((c || document).querySelectorAll(s));
	}
	function getAdminConfig() {
		const root = qs('.gops-admin');
		const fallback = {};
		if (root) {
			fallback.nonce = root.getAttribute('data-gops-nonce') || '';
			fallback.ajaxUrl = root.getAttribute('data-gops-ajax') || '';
		}
		return Object.assign({}, fallback, window.gopsAdmin || {});
	}

	function showNotice(type, message) {
		const wrap = qs('.gops-admin') || document;
		const header = qs('.gops-header', wrap) || qs('.gops-header');
		const box = ensureNoticesContainer(
			wrap,
			header || wrap.firstElementChild
		);
		if (!box) {
			return;
		}
		const notice = document.createElement('div');
		notice.className = 'notice notice-' + type + ' is-dismissible';
		const p = document.createElement('p');
		p.textContent = message;
		notice.appendChild(p);
		const btn = document.createElement('button');
		btn.type = 'button';
		btn.className = 'notice-dismiss';
		btn.innerHTML =
			'<span class="screen-reader-text">Dismiss this notice.</span>';
		btn.addEventListener('click', function () {
			notice.remove();
		});
		notice.appendChild(btn);
		box.appendChild(notice);
	}

	function setButtonLoading(btn, isLoading) {
		if (!btn) {
			return;
		}
		if (isLoading) {
			if (!btn.dataset.gopsOriginalText) {
				btn.dataset.gopsOriginalText = btn.textContent.trim();
			}
			btn.classList.add('is-loading');
			btn.disabled = true;
			if (!qs('.gops-spinner', btn)) {
				const spinner = document.createElement('span');
				spinner.className = 'gops-spinner';
				btn.appendChild(spinner);
			}
		} else {
			btn.classList.remove('is-loading');
			btn.disabled = false;
			const spinner = qs('.gops-spinner', btn);
			if (spinner) {
				spinner.remove();
			}
		}
	}

	function ajaxRequest(action, data) {
		const cfg = getAdminConfig();
		const url = cfg.ajaxUrl || window.ajaxurl || '';
		const payload = Object.assign(
			{
				action,
				nonce: cfg.nonce || '',
			},
			data || {}
		);
		return jQuery.post(url, payload);
	}

	function replaceTileHtml(slug, html) {
		if (!slug || !html) {
			return;
		}
		const tile = qs('.gops-tile[data-gops-tile="' + slug + '"]');
		if (tile) {
			tile.outerHTML = html;
		}
	}

	function updateUpdatesCount(count, updatableCount) {
		const tabs = qs('.gops-tabs');
		if (tabs) {
			let updatesTab = qs('[data-gops-tab="updates"]', tabs);
			if (count > 0) {
				if (!updatesTab) {
					const cfg = getAdminConfig();
					const href = cfg.updatesUrl || '';
					if (href) {
						updatesTab = document.createElement('a');
						updatesTab.className = 'gops-tab';
						updatesTab.setAttribute('data-gops-tab', 'updates');
						updatesTab.href = href;
						updatesTab.textContent = 'Updates';
						if (
							new URLSearchParams(window.location.search).get(
								'gops_filter'
							) === 'updates'
						) {
							updatesTab.classList.add('is-active');
						}
						const badge = document.createElement('span');
						badge.className = 'gops-tab__badge';
						badge.setAttribute('data-gops-updates-count', count);
						badge.textContent = String(count);
						updatesTab.appendChild(badge);
						const allTab = qs('[data-gops-tab="all"]', tabs);
						if (allTab && allTab.nextSibling) {
							tabs.insertBefore(updatesTab, allTab.nextSibling);
						} else {
							tabs.appendChild(updatesTab);
						}
					}
				} else {
					let badge = qs('.gops-tab__badge', updatesTab);
					if (!badge) {
						badge = document.createElement('span');
						badge.className = 'gops-tab__badge';
						updatesTab.appendChild(badge);
					}
					badge.setAttribute('data-gops-updates-count', count);
					badge.textContent = String(count);
				}
			} else if (updatesTab) {
				updatesTab.remove();
			}
		}

		const actionsWrap = qs('.gops-actions');
		if (actionsWrap) {
			const updateAllBtn = qs('.gops-update-all', actionsWrap);
			const effectiveUpdatableCount =
				typeof updatableCount !== 'undefined' ? updatableCount : count;
			if (effectiveUpdatableCount > 0) {
				actionsWrap.style.display = '';
				if (updateAllBtn) {
					updateAllBtn.textContent =
						'Update All (' + effectiveUpdatableCount + ')';
				}
			} else {
				actionsWrap.style.display = 'none';
			}
		}

		// Update WordPress sidebar menu badge
		const menuBadge = document.querySelector(
			'#toplevel_page_gravity_ops .update-plugins'
		);
		if (menuBadge) {
			if (count > 0) {
				menuBadge.className = 'update-plugins count-' + count;
				const inner = menuBadge.querySelector('.plugin-count');
				if (inner) {
					inner.textContent = String(count);
				}
			} else {
				menuBadge.remove();
			}
		}
	}

	function openChangelogModal(data) {
		const modal = qs('#gops-changelog-modal');
		if (!modal) {
			return;
		}
		const title = qs('.gops-modal__title', modal);
		const content = qs('.gops-modal__content', modal);
		const link = qs('.gops-modal__full-link', modal);
		if (title) {
			title.textContent = data.title || 'Changelog';
		}
		if (content) {
			content.innerHTML = data.changelog || 'Changelog not available.';
		}
		if (link) {
			if (data.full_url) {
				link.href = data.full_url;
				link.style.display = '';
			} else {
				link.style.display = 'none';
			}
		}
		modal.style.display = '';
		modal.classList.add('is-open');
		modal.setAttribute('aria-hidden', 'false');
	}

	function closeChangelogModal() {
		const modal = qs('#gops-changelog-modal');
		if (!modal) {
			return;
		}
		modal.classList.remove('is-open');
		modal.style.display = 'none';
		modal.setAttribute('aria-hidden', 'true');
	}

	// Relocate admin notices to appear just below our header on our pages and FS pages
	function ensureNoticesContainer(root, header) {
		if (!root || !header) {
			return null;
		}
		let box = qs('.gops-notices', root);
		if (!box) {
			box = document.createElement('div');
			box.className = 'gops-notices';
			box.setAttribute('aria-live', 'polite');
			header.insertAdjacentElement('afterend', box);
		}
		return box;
	}

	function moveNotices() {
		// GravityOps pages
		const wrap = qs('.gops-admin');
		if (wrap) {
			const header = qs('.gops-header', wrap);
			const box = ensureNoticesContainer(wrap, header);
			if (box) {
				const notices = qsa(
					'#wpbody-content .notice, #wpbody-content .updated, #wpbody-content .error, #wpbody-content .fs-notice, #wpbody-content .update-nag'
				);
				notices.forEach((n) => {
					if (n.parentElement !== box) {
						box.appendChild(n);
						n.classList.add('inline');
					}
				});
			}
		}

		// Freemius containers
		const fsWrap =
			qs('#fs_account') ||
			qs('.fs-section.fs-full-size-wrapper') ||
			qs('.wrap .fs-section');
		if (fsWrap) {
			const fsHeader = qs('.gops-header', fsWrap) || qs('.gops-header');
			const box = ensureNoticesContainer(
				fsWrap,
				fsHeader || fsWrap.firstElementChild
			);
			if (box) {
				qsa(
					'#wpbody-content .notice, #wpbody-content .updated, #wpbody-content .error, #wpbody-content .fs-notice, #wpbody-content .update-nag'
				).forEach(function (n) {
					if (n.parentElement !== box) {
						box.appendChild(n);
						n.classList.add('inline');
					}
				});
			}
		}
	}

	// Tile navigation and state handling
	document.addEventListener('click', function (e) {
		const tile = e.target.closest('.gops-tile');
		if (!tile) {
			return;
		}

		// FIX: Don't navigate if the user is selecting text
		const ownerWindow = e.target.ownerDocument.defaultView;
		if (ownerWindow.getSelection().toString().length > 0) {
			return;
		}

		// If click originated in a form/button/link inside actions, don't navigate
		if (
			e.target.closest('form') ||
			e.target.closest('button') ||
			e.target.closest('a') // FIX: Exclude ALL links, not just buttons
		) {
			return; // allow normal action
		}
		const state = tile.getAttribute('data-gops-state');
		const marketing = tile.getAttribute('data-gops-marketing-url') || '';
		const needsUpgrade =
			tile.getAttribute('data-gops-needs-upgrade') === '1';
		const pluginName =
			tile.getAttribute('data-gops-plugin-name') || 'this plugin';
		if (state === 'not-installed') {
			// Open pricing in new tab
			const url = marketing ? marketing + '#pricing' : '#';
			if (url && url !== '#') {
				window.open(url, '_blank', 'noopener');
			}
			return;
		}
		if (state === 'inactive') {
			// Show a one-time inline notice under our header
			const wrap = qs('.gops-admin') || document;
			const header = qs('.gops-header', wrap) || qs('.gops-header');
			const box = ensureNoticesContainer(
				wrap,
				header || wrap.firstElementChild
			);
			if (box && !qs('.gops-inline-notice', wrap)) {
				const notice = document.createElement('div');
				notice.className =
					'notice notice-warning is-dismissible gops-inline-notice';
				notice.innerHTML =
					'<p>This plugin is installed but not active. Use the Activate button on the card to enable it.</p>';
				box.appendChild(notice);
			}
			return; // Do not navigate
		}

		// Active but the new AdminShell page hasn't been registered yet → prompt to upgrade plugin and do not navigate
		if (state === 'active' && needsUpgrade) {
			const wrap = qs('.gops-admin') || document;
			const header = qs('.gops-header', wrap) || qs('.gops-header');
			const box = ensureNoticesContainer(
				wrap,
				header || wrap.firstElementChild
			);
			if (box) {
				const notice = document.createElement('div');
				notice.className =
					'notice notice-info is-dismissible gops-inline-notice';
				notice.innerHTML =
					'<p>' +
					'“' +
					pluginName +
					'” needs an update to open here. Please update it to the latest version from <a href="plugins.php">Plugins</a> or <a href="update-core.php">Updates</a>.' +
					'</p>';

				const btn = document.createElement('button');
				btn.type = 'button';
				btn.className = 'notice-dismiss';
				btn.innerHTML =
					'<span class="screen-reader-text">Dismiss this notice.</span>';
				btn.addEventListener('click', function () {
					notice.remove();
				});

				notice.appendChild(btn);
				box.appendChild(notice);
			}
			return;
		}

		const link = tile.querySelector('.gops-tile__link');
		if (link && link.href) {
			window.location.href = link.href;
		}
	});

	// Action buttons (update/activate/deactivate/changelog)
	document.addEventListener('click', function (e) {
		const btn = e.target.closest('button[data-gops-action]');
		if (!btn) {
			return;
		}

		const action = btn.getAttribute('data-gops-action') || '';
		if (!action) {
			return;
		}

		e.preventDefault();
		e.stopPropagation();

		const slug = btn.getAttribute('data-gops-slug') || '';
		const pluginFile = btn.getAttribute('data-gops-plugin-file') || '';

		if (action === 'changelog') {
			if (!slug) {
				showNotice('error', 'Missing plugin data.');
				return;
			}
			setButtonLoading(btn, true);
			ajaxRequest('gops_get_changelog', {
				slug,
				plugin: pluginFile,
			})
				.done(function (resp) {
					if (resp && resp.success) {
						openChangelogModal(resp.data || {});
					} else {
						const msg =
							(resp && resp.data && resp.data.message) ||
							'Unable to load changelog.';
						showNotice('error', msg);
					}
				})
				.fail(function () {
					showNotice('error', 'Unable to load changelog.');
				})
				.always(function () {
					setButtonLoading(btn, false);
				});
			return;
		}

		if (btn.classList.contains('is-loading')) {
			return;
		}

		let request = null;
		if (action === 'update') {
			request = ajaxRequest('gops_update_plugin', {
				slug,
				plugin: pluginFile,
			});
		} else if (action === 'update-all') {
			request = ajaxRequest('gops_update_all', {});
		} else if (action === 'activate' || action === 'deactivate') {
			request = ajaxRequest('gops_toggle_plugin', {
				slug,
				plugin: pluginFile,
				toggle: action,
			});
		}

		if (!request) {
			return;
		}

		setButtonLoading(btn, true);

		request
			.done(function (resp) {
				if (resp && resp.success) {
					const data = resp.data || {};
					if (data.tile_html && data.slug) {
						replaceTileHtml(data.slug, data.tile_html);
					}
					if (data.tiles) {
						Object.keys(data.tiles).forEach(function (tileSlug) {
							replaceTileHtml(tileSlug, data.tiles[tileSlug]);
						});
					}
					if (typeof data.updates_count === 'number') {
						updateUpdatesCount(
							data.updates_count,
							data.updatable_count
						);
					}
					if (data.message) {
						showNotice(
							data.errors && data.errors.length
								? 'warning'
								: 'success',
							data.message
						);
					}

					// Refresh all updates after a successful action to maintain consistency.
					if (
						action === 'update' ||
						action === 'update-all' ||
						action === 'activate' ||
						action === 'deactivate'
					) {
						triggerBackgroundRefresh();
					}
					if (data.errors && data.errors.length) {
						data.errors.forEach(function (err) {
							showNotice('error', err);
						});
					}
				} else {
					const msg =
						(resp && resp.data && resp.data.message) ||
						'Action failed.';
					showNotice('error', msg);
				}
			})
			.fail(function (resp) {
				let msg = 'Action failed.';
				if (resp && resp.responseJSON && resp.responseJSON.data) {
					msg = resp.responseJSON.data.message || msg;
				} else if (resp && resp.responseText) {
					msg =
						resp.responseText.trim() === '-1'
							? 'Security check failed. Refresh and try again.'
							: resp.responseText;
				}
				showNotice('error', msg);
			})
			.always(function () {
				setButtonLoading(btn, false);
			});
	});

	// Modal close actions
	document.addEventListener('click', function (e) {
		if (e.target.closest('[data-gops-modal-close]')) {
			e.preventDefault();
			closeChangelogModal();
		}
	});
	document.addEventListener('keydown', function (e) {
		if (e.key === 'Escape') {
			closeChangelogModal();
		}
	});

	// Freemius styling shim: hide native tabs and inject our header + full GravityOps pills
	function styleFreemius() {
		const pageParam =
			new URLSearchParams(window.location.search).get('page') || '';
		const isFreemius = /-(account|pricing|affiliation)$/.test(pageParam);
		if (!isFreemius) {
			return;
		}

		const fsWrap =
			qs(
				'#fs_account, .fs-section.fs-full-size-wrapper, .wrap .fs-section'
			) || qs('.wrap');
		if (!fsWrap) {
			return;
		}

		// Derive base slug (strip -account/-pricing/-affiliation)
		const baseSlug = pageParam.replace(
			/-(account|pricing|affiliation)$/,
			''
		);
		if (!baseSlug) {
			return;
		}

		const config = window.gops_admin_config || null;

		// Header injection
		if (!qs('.gops-header', fsWrap)) {
			const header = document.createElement('header');
			header.className = 'gops-header';
			const h1 = qs('h1, .fs-plugin-title', fsWrap);
			const raw = h1
				? h1.textContent.trim()
				: baseSlug.replace(/-/g, ' ');

			const titleText = (config && config.title) || raw;

			if (config && config.coupon && pageParam.endsWith('-pricing')) {
				const couponBanner = document.createElement('div');
				couponBanner.className = 'gops-coupon-banner';
				couponBanner.style.background = '#f0f6fa';
				couponBanner.style.border = '1px dashed #2271b1';
				couponBanner.style.padding = '10px';
				couponBanner.style.marginBottom = '15px';
				couponBanner.style.borderRadius = '4px';
				couponBanner.innerHTML = `<p style="margin:0; font-weight:600; color:#2271b1;">Special Gift: Get 10% Off Premium!</p>
                    <p style="margin:5px 0 0;">Use coupon code <code style="background:#fff; padding:2px 5px; border:1px solid #ccc; border-radius:3px;">${config.coupon}</code> at checkout.</p>`;
				fsWrap.insertBefore(couponBanner, fsWrap.firstChild);
			}

			header.innerHTML = `<div class="gops-header__left">
                           <a class="gops-logo-chip" href="admin.php?page=gravity_ops">GravityOps</a>
                           <div class="gops-headings">
                               <h1 class="gops-title">${titleText}</h1>
                           </div>
                       </div>`;
			fsWrap.insertBefore(header, fsWrap.firstChild);
			// Ensure a notices container exists after header
			ensureNoticesContainer(fsWrap, header);
		}

		// Pills injection: remove any existing .gops-tabs first to avoid wrong items
		qsa('.gops-tabs', fsWrap).forEach(function (el) {
			el.parentNode.removeChild(el);
		});

		// Run on DOM ready
		if (document.readyState === 'loading') {
			document.addEventListener('DOMContentLoaded', function () {
				moveNotices();
			});
		} else {
			moveNotices();
		}
		const nav = document.createElement('nav');
		nav.className = 'gops-tabs';

		// Determine core tabs per config
		let tabs = [];
		if (config && config.tabs && config.tabs.length > 0) {
			tabs = config.tabs;
		} else {
			// Fallback generic
			tabs.push(
				{
					id: 'overview',
					label: 'Overview',
					url: 'admin.php?page=' + baseSlug + '&tab=overview',
				},
				{
					id: 'feeds',
					label: 'Feeds',
					url: 'admin.php?page=' + baseSlug + '&tab=feeds',
				},
				{
					id: 'help',
					label: 'Help',
					url: 'admin.php?page=' + baseSlug + '&tab=help',
				}
			);

			// Freemius tabs fallback
			tabs.push(
				{
					id: 'account',
					label: 'Account',
					url: 'admin.php?page=' + baseSlug + '-account',
				},
				{
					id: 'affiliation',
					label: 'Affiliation',
					url: 'admin.php?page=' + baseSlug + '-affiliation',
				},
				{
					id: 'pricing',
					label: 'Pricing',
					url: 'admin.php?page=' + baseSlug + '-pricing',
				}
			);
		}

		tabs.forEach(function (t) {
			const a = document.createElement('a');
			const isActive = pageParam.endsWith('-' + t.id);
			a.className = 'gops-tab' + (isActive ? ' is-active' : '');
			a.href = t.url || t.href;
			a.textContent = t.label;
			nav.appendChild(a);
		});
		fsWrap.insertBefore(nav, fsWrap.firstChild.nextSibling);

		// Hide native freemius tab wrappers (CSS also hides, this is extra safety)
		qsa('.nav-tab-wrapper, .fs-tabs, .fs-submenu', fsWrap).forEach(
			function (el) {
				el.style.display = 'none';
			}
		);
	}

	// Run DOM adjustments
	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', function () {
			styleFreemius();
			moveNotices();
			applyFreePluginExternalTabTargets();
			triggerBackgroundRefresh();
		});
	} else {
		styleFreemius();
		moveNotices();
		applyFreePluginExternalTabTargets();
		triggerBackgroundRefresh();
	}

	function triggerBackgroundRefresh() {
		const root = qs('.gops-admin');
		if (root && root.dataset.gopsRefresh === '1') {
			const loader = qs('.gops-header-loader', root);
			if (loader) {
				loader.style.display = 'block';
			}
			const tiles = qsa('.gops-tile');
			const items = tiles.map(function (tile) {
				const slug = tile.dataset.gopsTile;
				const versionEl = qs('.gops-tile__version', tile);
				const version = versionEl
					? versionEl.textContent.replace('v', '').trim()
					: '0';
				return { slug, version };
			});

			ajaxRequest('gops_check_suite_updates', {
				items: JSON.stringify(items),
			})
				.done(function (resp) {
					if (resp && resp.success && resp.data) {
						const data = resp.data;
						if (data.tiles) {
							Object.keys(data.tiles).forEach(function (slug) {
								replaceTileHtml(slug, data.tiles[slug]);
							});
						}
						if (typeof data.updates_count === 'number') {
							updateUpdatesCount(
								data.updates_count,
								data.updatable_count
							);
						}
					}
				})
				.always(function () {
					if (loader) {
						loader.style.display = 'none';
					}
				});
		}
	}
	function applyFreePluginExternalTabTargets() {
		try {
			const anchors = qsa('.gops-tabs a');

			anchors.forEach(function (a) {
				const href = a.getAttribute('href') || '';
				if (!href) {
					return;
				}
				let url;
				try {
					url = new URL(href, window.location.href);
				} catch (e) {
					return;
				}

				// New-tab ONLY when link resolves to https://brightleafdigital.io/affiliate/ (any query/hash allowed).
				const isBrightleafOrigin =
					url.origin === 'https://brightleafdigital.io';
				const p = (url.pathname || '').toLowerCase();
				const isAffiliatePath =
					p === '/affiliate' || p.startsWith('/affiliate/');
				const isExternalAffiliate =
					isBrightleafOrigin && isAffiliatePath;

				if (isExternalAffiliate) {
					a.setAttribute('target', '_blank');
					a.setAttribute('rel', 'noopener');
				} else {
					// Everything else inside the tabs stays in the same tab (including Freemius -affiliation admin pages).
					a.removeAttribute('target');
					a.removeAttribute('rel');
				}
			});
		} catch (e) {
			// no-op
		}
	}
	jQuery(document).on('wp-notice-added', moveNotices);
})();
