/**
 * Content Protection – frontend script
 * Disables right-click, drag/drop, keyboard shortcuts, and text selection per config.
 * Shows a toast message when a disabled action is attempted.
 */
(function () {
	'use strict';

	var config = typeof wpPowersuiteContentProtection !== 'undefined' ? wpPowersuiteContentProtection : {};

	if (!config.message) config.message = 'This function is disabled';
	if (!config.messages) config.messages = {};
	if (!config.position) config.position = 'top-right';
	if (!config.duration) config.duration = 3000;

	function isEditableField(el) {
		if (!el || el.nodeType !== 1) {
			return false;
		}
		var tag = el.tagName;
		if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') {
			return true;
		}
		if (el.isContentEditable) {
			return true;
		}
		return !!(el.closest && el.closest('[contenteditable]'));
	}

	var toastEl = null;
	var toastTimer = null;

	function getMessage(featureKey) {
		return (config.messages && config.messages[featureKey]) || config.message;
	}

	function showToast(featureKey) {
		if (toastTimer) clearTimeout(toastTimer);
		if (toastEl && toastEl.parentNode) toastEl.parentNode.removeChild(toastEl);
		var message = getMessage(featureKey);
		toastEl = document.createElement('div');
		toastEl.className = 'wpps-cp-toast wpps-cp-toast--' + (config.position || 'top-right');
		toastEl.setAttribute('role', 'alert');
		var textEl = document.createElement('span');
		textEl.className = 'wpps-cp-toast__text';
		textEl.textContent = message;
		toastEl.appendChild(textEl);
		document.body.appendChild(toastEl);
		toastTimer = setTimeout(function () {
			if (toastEl && toastEl.parentNode) toastEl.parentNode.removeChild(toastEl);
			toastEl = null;
			toastTimer = null;
		}, config.duration);
	}

	// Disable right click
	if (config.disableRightClick) {
		document.addEventListener('contextmenu', function (e) {
			var t = e.target;
			if (t && typeof t.closest === 'function') {
				if (t.closest('[data-wpps-allow-context-menu="1"]')) {
					return;
				}
				if (t.closest('input, textarea, select, [contenteditable]')) {
					return;
				}
			}
			e.preventDefault();
			showToast('disableRightClick');
			return false;
		}, true);
	}

	// Disable drag/drop
	if (config.disableDragDrop) {
		function shouldAllowDrag(node) {
			if (!node || typeof node.closest !== 'function') {
				return false;
			}
			/** Sortables, draggable UI, etc. — same pattern as data-wpps-allow-context-menu / allow-text-select. */
			if (node.closest('[data-wpps-allow-drag="1"]')) {
				return true;
			}
			if (node.closest('input[type="file"], [data-wpps-allow-file-drop="1"]')) {
				return true;
			}
			var lbl = node.closest('label');
			if (!lbl) {
				return false;
			}
			if (lbl.querySelector('input[type="file"]')) {
				return true;
			}
			var fid = lbl.htmlFor;
			if (fid && document.getElementById) {
				var byFor = document.getElementById(fid);
				if (byFor && byFor.tagName === 'INPUT' && byFor.type === 'file') {
					return true;
				}
			}
			return false;
		}
		document.addEventListener('dragstart', function (e) {
			if (shouldAllowDrag(e.target)) {
				return;
			}
			e.preventDefault();
			showToast('disableDragDrop');
			return false;
		}, true);
		document.addEventListener('dragover', function (e) {
			if (shouldAllowDrag(e.target)) {
				return;
			}
			e.preventDefault();
			return false;
		}, true);
		document.addEventListener('drop', function (e) {
			if (shouldAllowDrag(e.target)) {
				return;
			}
			e.preventDefault();
			showToast('disableDragDrop');
			return false;
		}, true);
	}

	// Disable keyboard keys (only handlers for toggled shortcuts are evaluated).
	var k = config.disabledKeys || {};
	var activeKeys = [];
	var keyName;
	for (keyName in k) {
		if (k[keyName]) activeKeys.push(keyName);
	}
	function keyMatches(e, name) {
		var key = (e.key || '').toLowerCase();
		var code = (e.code || '').toLowerCase();
		var keyCode = e.keyCode;
		var ctrl = e.ctrlKey || e.metaKey;
		var alt = e.altKey;
		switch (name) {
			case 'devTools':
				return keyCode === 123
					|| (keyCode === 85 && ctrl)
					|| (keyCode === 73 && ctrl && e.shiftKey)
					|| (keyCode === 74 && ctrl && e.shiftKey)
					|| (keyCode === 83 && ctrl && e.shiftKey)
					|| (keyCode === 78 && ctrl && e.shiftKey);
			case 'search':
				return ctrl && (key === 'f' || key === 'g' || key === 'h' || key === 'k');
			case 'ctrlC': return ctrl && (key === 'c' || code === 'keyc');
			case 'ctrlV': return ctrl && (key === 'v' || code === 'keyv');
			case 'ctrlA': return ctrl && (key === 'a' || code === 'keya');
			case 'ctrlU': return ctrl && (key === 'u' || code === 'keyu');
			case 'ctrlP': return ctrl && (key === 'p' || code === 'keyp');
			case 'ctrlH': return ctrl && (key === 'h' || code === 'keyh');
			case 'ctrlL': return ctrl && (key === 'l' || code === 'keyl');
			case 'ctrlK': return ctrl && (key === 'k' || code === 'keyk');
			case 'ctrlO': return ctrl && (key === 'o' || code === 'keyo');
			case 'ctrlE': return ctrl && (key === 'e' || code === 'keye');
			case 'ctrlF3': return keyCode === 114 && ctrl;
			case 'altD': return alt && (key === 'd' || code === 'keyd');
			case 'f6': return keyCode === 117;
			case 'f12': return keyCode === 123;
			default: return false;
		}
	}
	if (activeKeys.length > 0) {
		document.addEventListener('keydown', function (e) {
			var i;
			var nm;
			for (i = 0; i < activeKeys.length; i++) {
				nm = activeKeys[i];
				if (!keyMatches(e, nm)) {
					continue;
				}
				if ((nm === 'ctrlC' || nm === 'ctrlV' || nm === 'ctrlA') && isEditableField(e.target)) {
					continue;
				}
				e.preventDefault();
				e.stopPropagation();
				showToast('disabledKeys');
				return false;
			}
		}, true);
	}

	// Disable text selection
	if (config.disableTextSelection) {
		document.addEventListener('selectstart', function (e) {
			var t = e.target;
			if (t && typeof t.closest === 'function') {
				if (t.closest('[data-wpps-allow-text-select="1"]')) {
					return;
				}
				if (t.closest('input, textarea, select, pre, code, [contenteditable]')) {
					return;
				}
			}
			e.preventDefault();
			showToast('disableTextSelection');
			return false;
		}, true);
		var style = document.createElement('style');
		style.textContent =
			'body{-webkit-user-select:none!important;-moz-user-select:none!important;-ms-user-select:none!important;user-select:none!important}' +
			'input,textarea,select,pre,code,[contenteditable],[data-wpps-allow-text-select="1"]{-webkit-user-select:text!important;-moz-user-select:text!important;-ms-user-select:text!important;user-select:text!important}';
		document.head.appendChild(style);
	}
})();
