/**
 * RSM Features — SiteOrigin shell chrome strip and hot chip popout modals.
 *
 * @package Rsmspark_Content_Widgets
 */
(function (window, document, $) {
	'use strict';

	function clearBorderShorthands(el) {
		el.style.removeProperty('border');
		el.style.removeProperty('border-top');
		el.style.removeProperty('border-right');
		el.style.removeProperty('border-bottom');
		el.style.removeProperty('border-left');
	}

	function applyImportantChromeStrip(el, props) {
		if (!el) {
			return;
		}
		try {
			clearBorderShorthands(el);
			for (var p = 0; p < props.length; p++) {
				el.style.setProperty(props[p][0], props[p][1], 'important');
			}
		} catch (e) {
			// Very old engines may not support the priority argument.
		}
	}

	function stripSiteOriginShellChrome() {
		var shellProps = [
			['border-width', '0'],
			['border-style', 'none'],
			['border-color', 'transparent'],
			['border-image', 'none'],
			['border-image-source', 'none'],
			['border-image-width', '0'],
			['border-image-slice', '0'],
			['box-shadow', 'none'],
			['outline', 'none'],
			['outline-width', '0'],
			['outline-style', 'none'],
			['filter', 'none'],
			['background', 'transparent'],
			['padding', '0'],
			['margin', '0'],
		];
		var cellChromeProps = [
			['border-width', '0'],
			['border-style', 'none'],
			['border-color', 'transparent'],
			['border-image', 'none'],
			['border-image-source', 'none'],
			['border-image-width', '0'],
			['border-image-slice', '0'],
			['box-shadow', 'none'],
			['outline', 'none'],
			['outline-width', '0'],
			['outline-style', 'none'],
			['filter', 'none'],
		];

		function shouldStripWrapper(el) {
			if (!el || !el.classList) {
				return false;
			}
			var cn = el.className || '';
			return (
				el.classList.contains('widget') ||
				el.classList.contains('so-panel') ||
				el.classList.contains('so-widget-features') ||
				el.classList.contains('panel-grid-cell') ||
				cn.indexOf('widget_') !== -1 ||
				cn.indexOf('panel-cell-style') !== -1 ||
				cn.indexOf('panel-widget-style') !== -1 ||
				cn.indexOf('panel-row-style') !== -1
			);
		}

		function stripAncestors(startEl) {
			if (!startEl) {
				return;
			}
			var cell = startEl.closest('.panel-grid-cell');
			if (cell) {
				var n = startEl.parentElement;
				while (n && n !== cell) {
					if (shouldStripWrapper(n)) {
						applyImportantChromeStrip(n, cellChromeProps);
					}
					n = n.parentElement;
				}
				applyImportantChromeStrip(cell, cellChromeProps);
				return;
			}
			var w = startEl.parentElement;
			var depth = 0;
			while (w && w !== document.body && depth++ < 8) {
				if (shouldStripWrapper(w)) {
					applyImportantChromeStrip(w, cellChromeProps);
				}
				w = w.parentElement;
			}
		}

		var roots = document.querySelectorAll('[data-rsmspark-features]');
		for (var i = 0; i < roots.length; i++) {
			var root = roots[i];
			var shell = root.closest('.so-widget-features');
			if (shell) {
				applyImportantChromeStrip(shell, shellProps);
				stripAncestors(shell);
			} else {
				stripAncestors(root);
			}
		}

		var panels = document.querySelectorAll('.so-panel.widget_features, .so-panel.rsmspark-features-so-panel');
		for (var j = 0; j < panels.length; j++) {
			if (panels[j].querySelector('[data-rsmspark-features]')) {
				applyImportantChromeStrip(panels[j], cellChromeProps);
			}
		}
	}

	function getModalState($root) {
		var existing = $root.data('rf-modal-state');
		if (existing) {
			return existing;
		}

		var $modal = $root.find('.rsmspark-features__modal');
		var state = {
			modal: $modal.get(0),
			dialog: $modal.find('.rsmspark-features__modal-dialog').get(0),
			body: $modal.find('.rsmspark-features__modal-body').get(0),
			closeButton: $modal.find('.rsmspark-features__modal-close').get(0),
			bodyClass: 'rsmspark-features-modal-open',
			trigger: null,
			onOpen: function (modalState) {
				var $body = $(modalState.body);
				if (typeof window.rsmCalendarPreparePopout === 'function') {
					window.rsmCalendarPreparePopout($body);
				}
				$(document).trigger('rsm-calendar:mount', [$body]);
			},
		};

		$root.data('rf-modal-state', state);
		return state;
	}

	function openModal($root, popoutId, $trigger) {
		if (!window.RsmCwModal) {
			return;
		}

		var $template = $root.find('[data-rf-popout-template="' + popoutId + '"]');
		if (!$template.length) {
			return;
		}

		var state = getModalState($root);
		state.trigger = $trigger && $trigger.length ? $trigger.get(0) : null;
		state.contentHtml = $template.html();

		var parsed = document.createElement('div');
		parsed.innerHTML = state.contentHtml;
		var title = parsed.querySelector('.rsmspark-features__popout-title');
		state.labeledBy = title && title.id ? title.id : '';

		window.RsmCwModal.open(state);
	}

	function closeModal($root) {
		var state = $root.data('rf-modal-state');
		if (!state || !window.RsmCwModal) {
			return;
		}
		window.RsmCwModal.close(state);
	}

	function initFeatures(root) {
		var $root = $(root);

		$root.off('.rf');
		$root.removeData('rf-init');

		if (!$root.is('[data-rf-popouts="1"]')) {
			return;
		}

		$root.data('rf-init', true);

		$root.on('click.rf', '.rsmspark-features__chip--hot', function (event) {
			if ($(event.target).closest('a').length) {
				return;
			}
			event.preventDefault();
			var popoutId = $(this).attr('data-rf-popout-id');
			if (!popoutId) {
				return;
			}
			openModal($root, popoutId, $(this));
		});

		$root.on('keydown.rf', '.rsmspark-features__chip--hot', function (event) {
			if (event.key !== 'Enter' && event.key !== ' ') {
				return;
			}
			if ($(event.target).closest('a').length) {
				return;
			}
			event.preventDefault();
			openModal($root, $(this).attr('data-rf-popout-id'), $(this));
		});

		$root.on('click.rf', '.rsmspark-features__modal-backdrop, .rsmspark-features__modal-close', function () {
			closeModal($root);
		});

		$root.on('click.rf', '.rsmspark-features__modal-dialog', function (event) {
			event.stopPropagation();
		});
	}

	function boot(scope) {
		if (!scope || scope === document) {
			stripSiteOriginShellChrome();
		}
		var $scope = scope && scope !== document ? $(scope) : $(document);
		$scope.find('[data-rsmspark-features]').addBack('[data-rsmspark-features]').each(function () {
			initFeatures(this);
		});
	}

	var pageShellStripScheduled = false;

	function initRsmFeaturesPage() {
		boot(document);
		if (!pageShellStripScheduled) {
			pageShellStripScheduled = true;
			window.setTimeout(stripSiteOriginShellChrome, 0);
			window.setTimeout(stripSiteOriginShellChrome, 150);
			window.setTimeout(stripSiteOriginShellChrome, 500);
			window.setTimeout(stripSiteOriginShellChrome, 1000);
		}
	}

	$(initRsmFeaturesPage);

	window.rsmFeaturesInit = boot;
	window.rsmFeaturesStripShell = stripSiteOriginShellChrome;
})(window, document, jQuery);
