/* global epPackLicensePopover, jQuery */
(function ($) {
	'use strict';

	var cfg = window.epPackLicensePopover;
	if (!cfg || !cfg.i18n) {
		return;
	}

	function str(key) {
		return (cfg.i18n && cfg.i18n[key]) || key;
	}

	var licensePopoverLastFocus = null;
	var licensePopoverEscBound = false;

	function closeLicensePopover() {
		var $root = $('#bdt-tb-license-popover-root');
		if (!$root.length) {
			return;
		}
		$root.attr('hidden', 'hidden').attr('aria-hidden', 'true');
		$(document).off('keydown.epPackLicensePopover');
		licensePopoverEscBound = false;
		var el = licensePopoverLastFocus;
		licensePopoverLastFocus = null;
		if (el && typeof el.focus === 'function') {
			try {
				el.focus({ preventScroll: true });
			} catch (err) {
				el.focus();
			}
		}
	}

	function bindLicensePopoverOnce() {
		var $root = $('#bdt-tb-license-popover-root');
		if (!$root.length || $root.data('epPackPopoverInit')) {
			return;
		}
		$root.data('epPackPopoverInit', true);
		var $license = $('#bdt-tb-license-popover-license');
		var $pricing = $('#bdt-tb-license-popover-pricing');
		var $backdrop = $root.find('.bdt-tb-license-popover__backdrop');
		var $btn = $('#bdt-tb-license-popover-dismiss');
		var $card = $('#bdt-tb-license-popover');

		$('#bdt-tb-license-popover-title').text(str('licensePopoverTitle'));
		$('#bdt-tb-license-popover-desc').text(str('licensePopoverBody'));
		$license.text(str('licensePopoverActivate'));
		$pricing.text(str('licensePopoverPricing'));
		$btn.text(str('licensePopoverDismiss'));
		if (cfg.packLicenseUrl) {
			$license.attr('href', cfg.packLicenseUrl);
		}
		if (cfg.pricingPageUrl) {
			$pricing.attr('href', cfg.pricingPageUrl);
		}

		$pricing.on('click', function () {
			closeLicensePopover();
		});

		$backdrop.on('click', function () {
			closeLicensePopover();
		});
		$btn.on('click', function () {
			closeLicensePopover();
		});
		$card.on('click', function (e) {
			e.stopPropagation();
		});
	}

	function showLicensePopover(anchorEl) {
		var $root = $('#bdt-tb-license-popover-root');
		if (!$root.length) {
			if (cfg.packLicenseUrl) {
				window.location.href = cfg.packLicenseUrl;
			}
			return;
		}
		bindLicensePopoverOnce();

		var wasHidden = !!$root.prop('hidden');

		var el =
			anchorEl && anchorEl.nodeType === 1
				? anchorEl
				: document.querySelector('.wrap > a.page-title-action');
		if (!el || !el.getBoundingClientRect) {
			return;
		}

		if (wasHidden) {
			licensePopoverLastFocus = document.activeElement;
			licensePopoverEscBound = false;
		}

		$root.removeAttr('hidden').attr('aria-hidden', 'false');

		var $pop = $('#bdt-tb-license-popover');
		$pop.css({ top: '', left: '', transform: '' });

		requestAnimationFrame(function () {
			var r = el.getBoundingClientRect();
			var margin = 12;
			var gap = 10;
			var width = $pop.outerWidth() || 320;
			var height = $pop.outerHeight() || 180;
			var cx = r.left + r.width / 2;
			var left = cx - width / 2;
			left = Math.max(margin, Math.min(left, window.innerWidth - width - margin));

			var top = r.bottom + gap;
			if (top + height > window.innerHeight - margin) {
				top = r.top - height - gap;
			}
			if (top < margin) {
				top = margin;
			}

			$pop.css({
				position: 'fixed',
				top: top + 'px',
				left: left + 'px',
				zIndex: 100060
			});

			if (!licensePopoverEscBound) {
				licensePopoverEscBound = true;
				$(document).on('keydown.epPackLicensePopover', function (ev) {
					if (ev.key === 'Escape') {
						closeLicensePopover();
					}
				});
			}

			window.setTimeout(function () {
				var $f = $('#bdt-tb-license-popover-license');
				if ($f.length) {
					$f.trigger('focus');
				}
			}, 0);
		});
	}

	function bindAddNewLock() {
		var link = document.querySelector('.wrap > a.page-title-action');
		if (!link) {
			return;
		}
		link.classList.add('ep-pack-add-new-license-locked');
		link.setAttribute('href', '#');
		link.setAttribute('role', 'button');
		link.setAttribute('aria-haspopup', 'dialog');
		if (!link.hasAttribute('tabindex')) {
			link.setAttribute('tabindex', '0');
		}

		link.addEventListener('click', function (e) {
			e.preventDefault();
			showLicensePopover(link);
		});
		link.addEventListener('keydown', function (e) {
			if (e.key === 'Enter' || e.key === ' ') {
				e.preventDefault();
				showLicensePopover(link);
			}
		});
	}

	$(function () {
		bindLicensePopoverOnce();
		bindAddNewLock();
	});
})(jQuery);
